2014-09-22 41 views
3

我很开始在python中使用线程。我需要一些帮助,我应该如何去: - 生成一个线程 - 做了一些有益的工作 - 等到线程完成 - 做了一些有益的工作如何等待产生的线程在python中完成?

我也不太清楚,如果我安全地产卵线。可能还需要一些帮助。

import threading 

def my_thread(self): 
    #wait for the server to respond.. 
    #..... 
    # I want to rung this method aside from my main task 


def main(): 
    a = threading.thread(target = my_thread) 
    a.start() 

    # do some useful stuff here..... 
    # i.e opening a file and reading a file 

    # now I want to wait for my_thread to finish 
    # HOW DO I WAIT FOR my_thread to finish???????? 

    # do some useful stuff here..... 

回答

5

您可以使用Thread.join。来自文档的几行。

等到线程终止。这会阻塞调用线程,直到调用join()方法的线程终止 - 通常或通过未处理的异常 - 或直到发生可选的超时。

对于你的例子,它会像。

def main(): 
    a = threading.thread(target = my_thread) 
    a.start() 
    a.join()