python 等待信号量
在Python中,等待信号量是一个非常重要的主题。它允许程序通过一种非阻塞方式等待某个条件的产生,而不需要消耗太多的CPU资源。Python提供了多种等待信号量的机制,其中最经常使用的是threading模块的Event和Condition。
import threading # 创建一个Condition对象 condition = threading.Condition() # 定义一个共享变量 shared_var = None def producer(): global shared_var # 临界区开始 with condition: # 生产数据 shared_var = "data" # 通知所有等待这个条件的线程 condition.notify_all() # 临界区结束 def consumer(): global shared_var # 临界区开始 with condition: # 避免虚假唤醒,如果共享变量不为None,就一直等待 while shared_var is None: condition.wait() # 消费数据 print(shared_var) # 临界区结束 # 创建生产者线程 producer_thread = threading.Thread(target=producer) # 创建消费者线程 consumer_thread = threading.Thread(target=consumer) # 启动线程 producer_thread.start() consumer_thread.start() # 等待线程履行结束 producer_thread.join() consumer_thread.join()
上面代码中的Event和Condition对象都是线程同步的工具。Event用于通知一个或多个等待线程某个事件已产生,而Condition则是更灵活的线程同步工具。Condition对象在内部保护一个等待列表,当一个线程调用wait()方法时,它会释放锁并把自己加入等待列表。当另外一个线程调用notify()或notify_all()方法时,它会通知所有正在等待这个条件的线程,这些线程将重新获得锁,继续履行。
文章来源:丸子建站
文章标题:python 等待信号量
https://www.wanzijz.com/view/89330.html