Python 在多线程上关闭一个线程 [英] Python close a thread on multithreading

查看:61
本文介绍了Python 在多线程上关闭一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简化我遇到的情况:我试图终止一个仍在 Python 2.7 中运行的线程,但我不知道该怎么做.

以这个简单的代码为例:

导入时间进口螺纹定义线程1():打印开始线程 1"而真:时间.睡眠(0.5)打印工作"thread1 = threading.Thread(target=thread1, args=())thread1.start()时间.sleep(2)打印杀死线程 1"thread2.stop()打印检查它是否有效:"打印线程是:" + str(thread1.isAlive())

线程 1 继续工作",我试图在主线程中杀死它.关于如何做到这一点的任何想法?我试过了:

threat1.terminate威胁1.停止威胁1.退出威胁1.end

这一切似乎都表明,没有办法真正用一行简单的代码来阻止它.你有什么建议?

解决方案

使用线程安全的 threading.Event() 终止一个 Thread 控制:

导入线程,时间def Thread_Function(运行):运行时.is_set():打印('运行')时间.sleep(1)如果 __name__ == '__main__':运行 = threading.Event()运行.set()thread = threading.Thread(target=Thread_Function, args=(running,))线程开始()时间.sleep(1)print('事件正在运行.clear()')运行.clear()print('等待线程终止')线程连接()打印(退出__main__")

<块引用>

输出:

运行跑步事件 running.clear()等到线程终止退出 __main__

使用 Python:3.4.2 测试

<小时>

在线演示:reply.it

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

这篇关于Python 在多线程上关闭一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆