我有這樣的代碼:如何使用多線程
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