线程工作不如预期
我正在尝试用 threading
模块测试一些东西,但我真的搞不懂为什么它不工作。我用的是Windows 8,不过我在一个Linux虚拟机上试过这段代码,结果也是一样,我是不是用错了线程?
import threading
# test.py
class Test:
def __init__(self):
self.connect()
def connect(self):
threading.Thread(target=self.loop, daemon=True).start()
def loop(self):
while True:
print("works?")
Test()
如果我在IDLE里运行这个代码,它运行得很好,但一旦我在命令提示符下试,就只打印一次“works?”,然后就卡住了,我也无法给它发送结束命令。
如果我把 threading.Thread(target=self.loop, daemon=True).start()
去掉,换成 self.loop()
,在命令提示符下就能正常工作。为什么使用 threading.Thread(target=self.loop, daemon=True)
就不行呢?
有没有什么建议可以让我在命令提示符下让它工作?
2 个回答
0
我找到了问题所在,所有我正在运行的线程都是守护线程(我需要这样设置,这样我才能在Windows上用Ctrl+C来结束它们),所以一旦任务完成,它们就会立刻退出。Python可能把IDLE这个环境当作非守护线程,所以它可以继续运行。但是命令提示符或终端不算线程,所以它们会立刻退出。这里有个解决办法。
import threading
class Test:
def __init__(self):
self.connect()
def connect(self):
threading.Thread(target=self.loop, daemon=True).start()
def loop(self):
while True:
print("works?")
NEEDS_STARTED = True
while True:
if NEEDS_STARTED:
Test()
或者你也可以试试这个方法
import threading
class Test:
def __init__(self):
self.connect()
def connect(self):
threading.Thread(target=self.loop).start()
def loop(self):
while True:
print("works?")
不过还是感谢大家的建议和评论。如果有人能更好地解释为什么之前的方法不行,那就太好了,这样如果有人遇到类似的问题也能更明白。
2
看起来你应该直接创建一个 Thread
,而不是先写一个类再让这个类去使用 Thread
的某个方法!
class Test(threading.Thread):
def __init__(self, **kwds):
super(Test, self).__init__(**kwds)
self.daemon = True
def run(self):
while True:
print("works?")
t = Test()
t.start()
至于为什么你的代码在 IDLE 中能运行,但在命令行下不行,我就不太清楚了。如果有更有经验的 Python 程序员想要补充这个答案,欢迎随时添加解释!