python关闭线程_Python在多线程上关闭线程

这篇博客探讨了在Python 2.7中如何终止正在运行的线程。作者遇到的问题是尝试停止一个无限循环的线程但未能成功。通过引入`threading.Event()`,创建了一个线程安全的方法来停止线程。示例代码展示了如何使用`Event`对象来设置和清除线程的运行状态,从而实现线程的优雅退出。通过调用`thread.join()`确保线程完全停止,最后输出确认线程已经结束。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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.

Take this simple code:

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())

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?

解决方案

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__")

Output:

running

running

Event running.clear()

Wait until Thread is terminating

EXIT __main__

Tested with Python:3.4.2

Online Demo: reply.it

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值