2016-08-05 35 views
0

我有一個代碼,這樣的事情,Python的線程收集

import threading 

class Mythread(threading.Thread): 
     def __init__(self): 
      threading.Thread.__init__(self) 
     def run(self): 
      print('do some processing') 

if __name__=='__main__': 
     while Ture: 
     val = raw_input('next thread') 
     t = MyThread() 
     t.start() 
     t.join() 

的問題是我怎麼能繼續與主要功能,而不會阻塞主要是因爲t.join()停止主到t沒有完成?

回答

0

您應該將代碼放在「代碼」標記中,否則它不可讀。 而你只需要做那樣的事情。

if name == 'main': 
    #Thread creation 
    allThreads = [] 
    while True: 
     val = raw_input('next thread') 
     newThread = MyThread() 
     newThread.start() 
     allThreads.append(newThread) 

    #You can do something here 

    #Waiting for all threads to stop 
    for thread in allThreads: 
     thread.join() 
+0

謝謝,主程序總是停留在while循環中,它將如何去#Waiting所有線程停止?我希望while循環(主要)是永遠的,並且需要收集線程停止。在while循環內。 –

+0

停止線程的條件是什麼? – Sygmei

+0

其實,我想要什麼,我只想開始線程,但不希望它返回到主線程。所以當那個線程中的任務完成時就釋放了這個線程。 –