Python中如何在特定条件触发时暂停其他线程运行?
解决方案:线程暂停/恢复同步机制
原代码中使用threading.Lock无法实现“暂停所有其他线程”的需求,因为Lock仅用于保证临界区的互斥访问,无法让其他线程主动暂停运行。要实现优先代码段执行时暂停其他线程的效果,可以使用threading.Condition结合全局标志来完成线程的同步控制。
核心思路
- 定义全局标志
pause_other_threads,标记是否需要暂停其他线程 - 使用
threading.Condition对象实现线程的等待与唤醒:标志为True时其他线程进入等待,标志为False时唤醒所有等待线程 - 优先线程触发条件时设置暂停标志,执行完优先代码段后清除标志并唤醒其他线程
- 其他线程在执行任务前检查标志状态,需暂停则进入等待
修改后的代码
import threading import string import random import time # 线程同步用的条件变量 condition = threading.Condition() # 标记是否需要暂停其他线程 pause_other_threads = False def anotherThread(): while True: with condition: # 循环检查暂停标志,直到标志被清除 while pause_other_threads: condition.wait() # 执行线程任务 print("Running anotherThread", flush=True) time.sleep(0.5) # 模拟任务耗时 def printAlphabet(): while True: print("Running printAlphabet", flush=True) rand = random.randint(0, 1000) print(rand) if rand < 250: # 设置暂停标志,通知其他线程进入等待 with condition: global pause_other_threads pause_other_threads = True # 执行优先代码段 print("Printing Alphabet", flush=True) for letter in string.ascii_lowercase: print(letter, end=" ", flush=True) time.sleep(0.1) print() # 换行 # 完成优先操作,恢复其他线程运行 with condition: pause_other_threads = False condition.notify_all() time.sleep(0.5) # 模拟任务间隔 def main(): # 创建持续运行的守护线程 t1 = threading.Thread(target=anotherThread, daemon=True) t2 = threading.Thread(target=printAlphabet, daemon=True) t1.start() t2.start() # 主线程保持运行,防止子线程被终止 while True: time.sleep(1) if __name__ == "__main__": main()
工作原理
threading.Condition内置锁机制,调用wait()会释放锁并让线程进入阻塞状态,直到被notify_all()唤醒- anotherThread每次执行任务前都会检查暂停标志,若为
True则进入等待,直到优先线程完成操作后被唤醒 - printAlphabet进入优先代码段前设置暂停标志,执行完成后清除标志并唤醒所有等待线程,确保这段时间内其他线程不会运行
这种方式在大型程序中性能影响极低,等待的线程处于阻塞状态不占用CPU资源,仅在同步状态变化时被唤醒,能有效保证优先操作不受干扰。
内容的提问来源于stack exchange,提问作者zohani
相关产品推荐
相关产品推荐

