从outsid控制python线程的运行时

2024-05-18 23:42:25 发布

您现在位置: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()函数的文章,但这不是我需要的。你知道吗


Tags: thetoselffalsetrueobjifis
1条回答
网友
1楼 · 发布于 2024-05-18 23:42:25

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

相关问题 更多 >

    热门问题