Python 在多线程上关闭一个线程

use*_*843 4 python multithreading

为了简化我遇到的情况:我试图终止一个仍在 Python 2.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())
Run Code Online (Sandbox Code Playgroud)

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

threat1.terminate
threat1.stop
threat1.quit
threat1.end
Run Code Online (Sandbox Code Playgroud)

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

sto*_*vfl 10

要终止Thread受控,使用线程安全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__")
Run Code Online (Sandbox Code Playgroud)

输出

running  
running  
Event running.clear()  
Wait until Thread is terminating  
EXIT __main__
Run Code Online (Sandbox Code Playgroud)

用 Python 测试:3.4.2


在线演示:reply.it