2012-03-02 96 views
15

我有這樣的代碼:如何使用多線程

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 

回答

12

首先,你應該使用更高級別的threading模塊並專門Thread類。 thread模塊不是你所需要的。

當你擴展這段代碼時,你很可能也想等待線程完成。以下是如何使用join方法來實現,一個示範:

import threading 

class print_out(threading.Thread): 

    def __init__ (self, m1, m2): 
     threading.Thread.__init__(self) 
     self.m1 = m1 
     self.m2 = m2 

    def run(self): 
     print self.m1 
     print self.m2 
     print "\n" 

threads = [] 
for num in range(0, 10): 
    thread = print_out('a', 'b') 
    thread.start() 
    threads.append(thread) 

for thread in threads: 
    thread.join() 
+0

'thread.join()'用於等待線程終止。我注意到如果我不添加最後兩行代碼:'對於線程中的線程:thread.join()',程序也運行良好,並且每個線程都根據調試在'thread.start()'執行,IOW如果我不添加'time.time(0.1)',我不需要添加代碼'thread.join()',因爲程序會自動等待線程在'thread.start()'完成任務,對吧? – Searene 2012-03-02 11:34:10

+0

@Mark您根本不需要添加'time.sleep(0.1)'。這沒有必要。是的,您可以刪除調用「join」的代碼,Python環境將在終止執行之前等待所有線程完成。但是,我將這些調用添加到'join'中,因爲我期望在將來的某個時刻,您需要知道如何等待線程完成其執行。但是,是的,您可以在這個簡單的示例中簡單地省略那些對「join」的調用。 – 2012-03-02 11:47:27

2

你應該讓主線程活路了一小會兒。如果主線程死了,所有其他線程也會死掉,因此你將看不到任何輸出。嘗試在代碼的末尾添加time.sleep(0.1),然後您將看到輸出。

之後,您可以看看thread.join()以瞭解更多信息。

2

另一種方法是使用線程類。

instance[num]=threading.Thread(target=print_out, args=('a', 'b')) 

instance[num].start()