Python 简明教程
Python - Interrupting a Thread
在 Python 中中断线程是多线程编程中的一个常见需求,其中线程的执行需要在特定条件下终止。在多线程程序中,可能需要停止新线程中的任务。这可能是由于多种原因,例如任务完成、应用程序关闭或其他外部条件。
Interrupting a thread in Python is a common requirement in multi-threaded programming, where a thread’s execution needs to be terminated under certain conditions. In a multi-threaded program, a task in a new thread, may be required to be stopped. This may be for many reasons, such as − task completion, application shutdown, or other external conditions.
在 Python 中,可以使用 threading.Event 或在线程本身内设置终止标志来中断线程。这些方法使你能有效地中断线程,确保适当释放资源并且线程干净地退出。
In Python, interrupting threads can be achieved using threading.Event or by setting a termination flag within the thread itself. These methods allow you to interrupt the threads effectively, ensuring that resources are properly released and threads exit cleanly.
Thread Interruption using Event Object
中断线程的直接方法之一是使用 threading.Event 类。此类允许一个线程向另一个线程发出信号,表示发生了特定事件。以下是你可以使用 threading.Event 实现线程中断的方式:
One of the straightforward ways to interrupt a thread is by using the threading.Event class. This class allows one thread to signal to another that a particular event has occurred. Here’s how you can implement thread interruption using threading.Event
Example
在此示例中,我们有一个类 MyThread。它的对象开始执行 run() 方法。主线程休眠一段时间,然后设置一个事件。直至检测到事件,run() 方法中的循环才会继续。只要检测到事件,循环就会终止。
In this example, we have a MyThread class. Its object starts executing the run() method. The main thread sleeps for a certain period and then sets an event. Till the event is detected, loop in the run() method continues. As soon as the event is detected, the loop terminates.
from time import sleep
from threading import Thread
from threading import Event
class MyThread(Thread):
def __init__(self, event):
super(MyThread, self).__init__()
self.event = event
def run(self):
i=0
while True:
i+=1
print ('Child thread running...',i)
sleep(0.5)
if self.event.is_set():
break
print()
print('Child Thread Interrupted')
event = Event()
thread1 = MyThread(event)
thread1.start()
sleep(3)
print('Main thread stopping child thread')
event.set()
thread1.join()
执行此代码时,它将生成以下 output -
When you execute this code, it will produce the following output −
Child thread running... 1
Child thread running... 2
Child thread running... 3
Child thread running... 4
Child thread running... 5
Child thread running... 6
Main thread stopping child thread
Child Thread Interrupted
Thread Interruption using a Flag
中断线程的另一种方法是使用 flag ,该线程会定期检查该线程。此方法涉及在线程对象中设置一个标志属性,并在线程的执行循环中定期检查其值。
Another approach to interrupting threads is by using a flag that the thread checks at regular intervals. This method involves setting a flag attribute in the thread object and regularly checking its value in the thread’s execution loop.
Example
此示例演示了如何在 Python 多线程程序中使用标志来控制和停止正在运行的线程。
This example demonstrates how to use a flag to control and stop a running thread in Python multithreaded program.
import threading
import time
def foo():
t = threading.current_thread()
while getattr(t, "do_run", True):
print("working on a task")
time.sleep(1)
print("Stopping the Thread after some time.")
# Create a thread
t = threading.Thread(target=foo)
t.start()
# Allow the thread to run for 5 seconds
time.sleep(5)
# Set the termination flag to stop the thread
t.do_run = False
执行此代码时,它将生成以下 output -
When you execute this code, it will produce the following output −
working on a task
working on a task
working on a task
working on a task
working on a task
Stopping the Thread after some time.