Python在多线程上关闭线程

2024-04-27 15:00:52 发布

您现在位置:Python中文网/ 问答频道 /正文

为了简化我遇到的情况:我试图在一个线程仍在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

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


Tags: 代码importtimedef情况sleep线程thread
3条回答

通常,在这种情况下,我使用某种信号:

import time
import threading

class thread1(threading.Thread):

    def run(self):
        self.kill = False
        print "Starting thread 1"
        while not self.kill:
                time.sleep(0.5)
                print "Working"

thread_obj = thread1()
thread_obj.start()

time.sleep(2)
print "Killing thread 1"
thread_obj.kill = True
print "Checking if it worked:"
time.sleep(1)
print "Thread is: " + str(thread_obj.isAlive())

编辑

在阅读了评论中建议的答案后。。。我意识到这只是这里描述的一个简化版本。我希望这对你有用。

真的!

threads cannot be destroyed, stopped, suspended, resumed, or interrupted

(比如说下面一段中的文档the link。)

让您的线程监听您可能通过队列(最佳)、共享变量(较差)或任何其他方式发送的信号。小心,不要让它们运行未经检查的循环,如您的示例代码中所示。

要终止由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__")

Output:

running  
running  
Event running.clear()  
Wait until Thread is terminating  
EXIT __main__

使用Python测试:3.4.2

相关问题 更多 >