2016-08-05 46 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

其实,我想要什么,我只想开始线程,但不希望它返回到主线程。所以当那个线程中的任务完成时就释放了这个线程。 –