ste*_*ano 4 python multithreading
我需要运行一系列(无限循环)无限循环,必须能够检查外部设置条件才能终止.我认为线程模块会允许这样做,但我的努力如此失败.这是我想要做的一个例子:
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
Run Code Online (Sandbox Code Playgroud)
我原本期望t.start在一个单独的线程中运行,l的属性仍然可以访问.这不是发生的事情.我在python shell(IPython)中尝试了上面的代码片段.在实例化之后立即执行t start并且它阻止任何进一步的输入.很明显我对线程模块没有正确的看法.有关如何解决问题的任何建议?
你打电话runForever太早了.target = l.runForever不带括号使用.
函数调用在其参数之后才会被计算.当你编写时runforever(),它会在创建线程之前调用函数.通过传递runForever,您传递函数对象本身,然后线程设备可以在准备好时调用它.关键是你实际上并不想打电话runForever; 你只是想告诉线程代码,runForever就是它应该再打.