如何使主线程在启动内部线程后等待内部线程



如何使主线程在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)

函数

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)

这些行将在for循环中从my_threads中删除元素,因此您不会等待所有线程完成。

如果删除这些行,则代码将等待线程正确连接。然后,如果您认为需要删除线程,则可以在waitForThread返回时执行此操作(例如,使用del)。

带回家的课程是不要修改元素列表 - 至少不是通过添加或删除元素来修改您在for循环中循环的元素。那通常会产生奇怪的效果。

最新更新