停止线程 Python [英] Stop a thread Python
本文介绍了停止线程 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码,我怎样才能从 func1 中停止 func2?Thread(target = func1).stop()
之类的东西不起作用
i've got this code, how can I stop func2 from func1? something like Thread(target = func1).stop()
doesn't work
import threading
from threading import Thread
def func1():
while True:
print 'working 1'
def func2():
while True:
print 'Working2'
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
推荐答案
最好要求您的另一个线程停止,例如使用消息队列.
It's better to ask your other thread to stop, using a message queue for instance.
import time
import threading
from threading import Thread
import Queue
q = Queue.Queue()
def func1():
while True:
try:
item = q.get(True, 1)
if item == 'quit':
print 'quitting'
break
except:
pass
print 'working 1'
def func2():
time.sleep(10)
q.put("quit")
while True:
time.sleep(1)
print 'Working2'
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
这篇关于停止线程 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文