我正在尝试生成一个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()
函数的文章,但这不是我需要的。你知道吗
问题行是
t = threading.Thread(target=self.print_hello())
,更具体地说是target=self.print_hello()
。这将target
设置为self.print_hello()
的结果,并且由于此函数永不结束,因此将永远不会设置它。您需要做的是用t = threading.Thread(target=self.print_hello)
将它设置为函数本身。你知道吗相关问题 更多 >
编程相关推荐