如果您想要指定暂停和继续某一个线程,而不是所有线程,可以使用线程特定的条件变量来实现。以下是一个示例,演示如何暂停和继续特定线程:
import threading
import time
# 创建一个条件变量和标志变量,用于控制线程的暂停和继续
thread_1_paused = False
thread_2_paused = False
thread_1_cond = threading.Condition()
thread_2_cond = threading.Condition()
def thread_1_function():
global thread_1_paused
while True:
with thread_1_cond:
while thread_1_paused:
thread_1_cond.wait()
print("Thread 1 is running...")
time.sleep(1)
def thread_2_function():
global thread_2_paused
while True:
with thread_2_cond:
while thread_2_paused:
thread_2_cond.wait()
print("Thread 2 is running...")
time.sleep(1)
# 启动线程
thread_1 = threading.Thread(target=thread_1_function)
thread_2 = threading.Thread(target=thread_2_function)
thread_1.start()
thread_2.start()
# 暂停特定线程
def pause_thread(thread, cond):
global thread_1_paused, thread_2_paused
with cond:
if thread == thread_1:
thread_1_paused = True
elif thread == thread_2:
thread_2_paused = True
cond.notify()
# 继续特定线程
def resume_thread(thread, cond):
global thread_1_paused, thread_2_paused
with cond:
if thread == thread_1:
thread_1_paused = False
elif thread == thread_2:
thread_2_paused = False
cond.notify()
# 暂停和继续特定线程
pause_thread(thread_1, thread_1_cond)
time.sleep(2) # 暂停 2 秒
resume_thread(thread_1, thread_1_cond)
在此示例中,我们创建了两个条件变量 thread_1_cond
和 thread_2_cond
,以及两个标志变量 thread_1_paused
和 thread_2_paused
,用于控制线程 1 和线程 2 的暂停和继续。通过调用 pause_thread()
和 resume_thread()
函数,您可以控制特定线程的行为。
这个示例只是一个演示,您可以根据您的需求扩展和修改来管理多个线程的暂停和继续。请确保在线程同步方面小心操作,以避免潜在的竞态条件和死锁问题。