Python 2:线程停止运行,我不知道为什么
我试图让一个线程在后台循环运行,我可以使用 gui 按钮将 Thread 对象的 go 属性设置为 false 来关闭它。然而,该线程只运行一瞬间。
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.go = True
def run(self):
while self.go:
print "okay!"
这应该连续打印“好吧!”但事实并非如此。起初它什么也不做。然后,当我按 gui 按钮停止它,然后启动 MyThread 的另一个实例时,它会打印大约 50 行并停止。
我正在运行 Ubuntu Linux 11.04 和 python 2.7.1
I am trying to have a thread run in the background that loops that I can turn off with a gui button that sets the go property of the Thread object to false. However the thread only runs for a split second.
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.go = True
def run(self):
while self.go:
print "okay!"
This should continuously print "okay!" but it doesn't. At first it does nothing. Then when I press the gui button to stop it and then start another instance of MyThread it then prints about 50 lines and stops.
I am running Ubuntu Linux 11.04 with python 2.7.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,在 Python 中,所有线程(使用解释器)都受 GIL 约束,因此任何时候都只有一个线程在运行 Python 代码。这意味着如果 python 中有一个繁忙循环在一个线程中保存 GIL,它将停止另一个线程的执行。要了解有关 GIL 的更多信息,请查看 David Beazley 的演示:http://www.dabeaz.com/吉尔/
Remember that in python all threads (that use the interpreter) are subject to the GIL, and so there is only ever one thread running python code at any time. This means that if you have a busy loop in python land holding the GIL in one thread, it will stop execution of another thread. To read more about the GIL, have a look at David Beazley's presentations here: http://www.dabeaz.com/GIL/