Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python线程中运行和停止无限循环_Python_Multithreading - Fatal编程技术网

如何在python线程中运行和停止无限循环

如何在python线程中运行和停止无限循环,python,multithreading,Python,Multithreading,我需要运行(一系列)无限循环,必须能够检查外部设置的终止条件。我原以为线程模块会允许这样做,但我的努力失败了。下面是我正在尝试做的一个例子: import threading class Looping(object): def __init__(self): self.isRunning = True def runForever(self): while self.isRunning == True: "do stuff he

我需要运行(一系列)无限循环,必须能够检查外部设置的终止条件。我原以为线程模块会允许这样做,但我的努力失败了。下面是我正在尝试做的一个例子:

import threading

class Looping(object):

    def __init__(self):
     self.isRunning = True

    def runForever(self):
       while self.isRunning == True:
          "do stuff here"

l = Looping()
t = threading.Thread(target = l.runForever())
t.start()
l.isRunning = False
我希望t.start在一个单独的线程中运行,l的属性仍然可以访问。事实并非如此。我在pythonshell(IPython)中尝试了上面的代码片段。实例化后立即开始执行t,并阻止任何进一步的输入。 关于线程模块,我显然有一些地方不太对劲。
对如何解决这个问题有什么建议吗

您呼叫
永远运行
太早了。使用不带括号的
target=l.runForever


函数调用只有在其参数被指定后才进行求值。当您编写
runforever()
时,它会在创建线程之前立即调用函数。只需传递
runForever
,就可以传递函数对象本身,线程设备可以在准备好后调用它。关键是您实际上不想调用
runForever
;您只想告诉线程代码,
runForever
是它以后应该调用的。他们仍然让我受挫(我使用python的经验还不到一个月)。谢谢