2017-09-15 89 views
0

如何讓主線程在python中啓動後等待內部線程?如何讓主線程啓動後等待內部線程?

我使用join這個,但它不能正常工作,我認爲這是因爲內部線程調用time.sleep()。 任何想法?

這裏是代碼塊中:

def execution(start,end): 
    for i in range (start,end): 
     main() 
    return 

def waitForThread(delay,my_threads): 
    time.sleep (delay) 
    for t in my_threads: 
     t.join() 
     if t in my_threads: 
      my_threads.remove (t) 
    return 

def task(user,sleep): # it has multiple time.sleep() 
    #do some actions 
    time.sleep() 
    #do some actions 
    time.sleep() 
    return 

def main(): 
    threads=[] 
    for user in accounts: 
     t = Thread (target=task,args=(sleep-time,user)) 
     t.start() 
     threads.append (t) 
    waitForThread (130,threads) 

    ## I want the code stop here and when the execution of threads finished continue 

    ## doing other staff here 

    return 

if __name__ == '__main__': 
    execution(1,30) 

回答

2

功能

def waitForThread(delay,my_threads): 
    time.sleep (delay) 
    for t in my_threads: 
     t.join() 
     if t in my_threads: 
      my_threads.remove (t) 
    return 

看起來腥。尤其是線

 if t in my_threads: 
      my_threads.remove (t) 

這些線路將在my_threads循環for內移除元素,因此你不會等待所有線程完成。

如果刪除這些行,代碼將等待線程正常加入。然後,如果您覺得需要刪除線程,則可以在waitForThread返回時執行此操作(例如,使用del)。

回家的教訓是不要修改在for循環中循環的元素列表 - 至少不要添加或刪除元素。這往往有奇怪的影響。

+0

我嚴重懷疑,只是刪除這些行將使代碼基於OP的答案中的不可運行的代碼工作。 – martineau

+0

@martineau好的,我修改了我的答案以解決OP中詢問的特定問題。 – JohanL