2011-11-24 155 views
1
thread.start_new_thread(target=self.socketFunctionRead1()) 
print "Thread 1" 
thread.start_new_thread(target=self.socketFunctionWrite1()) 
print "Thread 2" 
thread.start_new_thread(target=self.socketFunctionRead2()) 
print "Thread 3" 
thread.start_new_thread(target=self.socketFunctionWrite2()) 
print "Thread 4" 

我想啓動多個線程,但只有一個線程啓動,我怎樣才能讓程序進一步通過啓動其他線程?Python線程:只有一個線程啓動

回答

2

相反的thread.start_new_thread(target=self.socketFunctionRead1())

嘗試由於parenthese的thread.start_new_thread(target=self.socketFunctionRead1)

,調用該函數和的返回值功能被分配給目標。由於thread.start_new_thread(target=self.socketFunctionRead1())可能是一個阻塞調用,只有這個函數被調用。

在thread.start_new_thread中,目標應該是可調用的(一個對象的行爲像一個函數)。

編輯:

Python documentation

thread.start_new_thread(函數,ARGS [,kwargs])

開始一個新的線程 和返回它的識別符。該線程使用參數列表args(它必須是一個元組)執行功能函數 。可選的 kwargs參數指定關鍵字參數的字典。當 函數返回時,該線程靜靜地退出。當函數 以未處理的異常終止時,將打印堆棧跟蹤,然後線程退出(但其他線程繼續運行) 。

這意味着你應該調用thread.start_new_thread(self.socketFunctionRead1)。

如果您將關鍵字參數傳遞給start_new_thread,它們將傳遞給self.socketFunctionRead1。

您的線程的目標是必需的,而不是關鍵字參數。

+1

現在我得到了:start_new_thread()不帶任何關鍵字參數:/ –

0

也許你只是從來沒有等待線程結束前退出程序...

當程序結束時,退出,並殺死所有線程。您必須等待所有線程結束前退出你的程序,就像埃米爾Akaydın說