我有这样的代码:如何使用多线程
import thread
def print_out(m1, m2):
print m1
print m2
print "\n"
for num in range(0, 10):
thread.start_new_thread(print_out, ('a', 'b'))
我要创建10个线程,每个线程运行功能print_out
,但我失败了。这些错误如下:
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
'thread.join()'用于等待线程终止。我注意到如果我不添加最后两行代码:'对于线程中的线程:thread.join()',程序也运行良好,并且每个线程都根据调试在'thread.start()'执行,IOW如果我不添加'time.time(0.1)',我不需要添加代码'thread.join()',因为程序会自动等待线程在'thread.start()'完成任务,对吧? – Searene 2012-03-02 11:34:10
@Mark您根本不需要添加'time.sleep(0.1)'。这没有必要。是的,您可以删除调用“join”的代码,Python环境将在终止执行之前等待所有线程完成。但是,我将这些调用添加到'join'中,因为我期望在将来的某个时刻,您需要知道如何等待线程完成其执行。但是,是的,您可以在这个简单的示例中简单地省略那些对“join”的调用。 – 2012-03-02 11:47:27