Python在多线程上关闭线程 [英] Python close a thread on multithreading
本文介绍了Python在多线程上关闭线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为简化这种情况,我正在尝试终止一个仍在Python 2.7中运行的线程,但我不确定该怎么做.
To simplify the situation I'm having: I'm trying to terminate a thread while it is still running in Python 2.7, and I'm not sure how to do it.
使用以下简单代码:
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一直处于工作状态",我正在尝试在主线程中将其杀死.关于如何做的任何想法?我尝试过:
Thread 1 keeps on 'working' and I'm trying to kill it in the main thread. Any idea on how to do it? I've tried:
threat1.terminate
threat1.stop
threat1.quit
threat1.end
这一切似乎都表明,没有办法通过简单的代码来真正阻止它.你有什么建议?
This all seems to point that there is no way to really stop it with a simple line of code. What could you suggest?
推荐答案
使用线程安全threading.Event()
终止Thread
控件:
To terminate an Thread
controlled, using a threadsafe threading.Event()
:
import threading, time
def Thread_Function(running):
while running.is_set():
print('running')
time.sleep(1)
if __name__ == '__main__':
running = threading.Event()
running.set()
thread = threading.Thread(target=Thread_Function, args=(running,))
thread.start()
time.sleep(1)
print('Event running.clear()')
running.clear()
print('Wait until Thread is terminating')
thread.join()
print("EXIT __main__")
输出:
running
running
Event running.clear()
Wait until Thread is terminating
EXIT __main__
使用Python:3.4.2测试
Tested with Python:3.4.2
在线演示: reply.it
这篇关于Python在多线程上关闭线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文