2016-11-18 66 views
0

我试图根据一定的条件重复执行特定操作的python线程。如果条件不满足,则该线程应退出。我写了下面的代码,但它的运行无限期。从外部控制python线程的运行时间

class dummy(object): 
def __init__(self): 
    # if the flag is set to False,the thread should exit 
    self.flag = True 

def print_hello(self): 
    while self.flag: 
     print "Hello!! current Flag value: %s" % self.flag 
     time.sleep(0.5) 

def execute(self): 
    t = threading.Thread(target=self.print_hello()) 
    t.daemon = True # set daemon to True, to run thread in background 
    t.start() 


if __name__ == "__main__": 
    obj = dummy() 
    obj.execute() 
    #Some other functions calls 
    #time.sleep(2) 
    print "Executed" # This line is never executed 
    obj.flag = False 

我是python线程模块的新手。我已经通过一些文章暗示使用threading.Timer()函数,但这不是我所需要的。

回答

0

问题行是t = threading.Thread(target=self.print_hello()),更具体地说是target=self.print_hello()。这将target设置为self.print_hello()的结果,并且由于该功能永不结束,所以它永远不会被设置。你需要做的是用t = threading.Thread(target=self.print_hello)将它设置为函数本身。