为了简化我遇到的情况:我试图在一个线程仍在Python2.7中运行时终止它,但我不确定如何完成它。
使用以下简单代码:
import time
import threading
def thread1():
print "Starting thread 1"
while True:
time.sleep(0.5)
print "Working"
thread1 = threading.Thread(target=thread1, args=())
thread1.start()
time.sleep(2)
print "Killing thread 1"
thread2.stop()
print "Checking if it worked:"
print "Thread is: " + str(thread1.isAlive())
线程1继续“工作”,我试图在主线程中终止它。你知道怎么做吗?我试过:
threat1.terminate
threat1.stop
threat1.quit
threat1.end
这一切似乎都表明,没有办法用一行简单的代码来真正阻止它。你有什么建议吗?
通常,在这种情况下,我使用某种信号:
编辑
在阅读了评论中建议的答案后。。。我意识到这只是这里描述的一个简化版本。我希望这对你有用。
真的!
(比如说下面一段中的文档the link。)
让您的线程监听您可能通过队列(最佳)、共享变量(较差)或任何其他方式发送的信号。小心,不要让它们运行未经检查的循环,如您的示例代码中所示。
要终止由
Thread
控制的,请使用线程安全的threading.Event()
:使用Python测试:3.4.2
相关问题 更多 >
编程相关推荐