简体   繁体   English

为什么第二个线程没有启动?

[英]Why is the 2nd thread not starting?

This code doesn't give me the output I expect. 这段代码没有给我我期望的输出。 Something must be wrong, but I cannot understand what it could be. 一定有问题,但我不知道可能是什么。

import thread
import time

def func1(threadName, sleepTime):
    while 1 < 2:
        time.sleep(sleepTime)
        print "%s" % (threadName)

def func2(threadName, sleepTime):
    while 1 < 2:
        time.sleep(sleepTime)
        print "%s" % (threadName)


try:
    thread.start_new_thread(func1("slow" , 5))
    thread.start_new_thread(func2("fast" , 1))
except Exception, e:
    print str(e)

The output I expect is something like: 我期望的输出是这样的:

fast
fast
fast
fast
slow
fast

and so on, but only the 1st thread seems to be starting. 依此类推,但似乎只有第一个线程正在启​​动。 I implemented the "try and except" block later to see if there's an error somewhere but no error! 稍后我实现了“ try andexcept”块,以查看某处是否有错误,但没有错误!

It looks like the functions are being called before the threads are started. 看起来好像在线程启动之前就调用了函数。 I'm not very familiar with Python, but try: 我对Python不太熟悉,但是请尝试:

thread.start_new_thread(func1, ("slow" , 5))
thread.start_new_thread(func2, ("fast" , 1))

Notice the comma after the function name - you pass in the function as one argument, and a tuple of the argument parameters as a separate argument. 注意函数名称后的逗号-您将函数作为一个参数传递,并将参数参数的元组作为单独的参数传递。 This lets start_new_thread call your function when the new thread is ready. 这样,当新线程就绪时, start_new_thread调用您的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM