python中Event实现线程间同步介绍
前言:
Event在python线程间同步是一种常用的方法,本博客以生产者线程和工作者线程为例说明Event在线程间进行10次同步的应用。
import threading
from threading import Event, Thread
import time
import random
from time import sleep
pevent = Event() #默认是没有事件的
pevent.clear()
cevent = Event()
cevent.clear()
runtimes = 10
mutex_lock = threading.Lock()
class ProducerThread (threading.Thread):
def __init__(self, name, runflag):
threading.Thread.__init__(self)
self.name = name
self.runflag = runflag
self.continueflag = Event()
self.continueflag.set()
def run(self):
global runtimes
sleep(1)
print ("开始线程:" + self.name)
while self.continueflag.isSet():
print("wait consumer ...")
if runtimes == 0:
self.continueflag.clear()
break
pevent.wait()
print("come an consumer ...")
mutex_lock.acquire()
runtimes = runtimes - 1
mutex_lock.release()
pevent.clear()
sleep(1)
cevent.set()
print ("退出线程:" + self.name)
self.runflag.set()
class ConsumerThread (threading.Thread):
def __init__(self,name, runflag):
threading.Thread.__init__(self)
self.name = name
self.runflag = runflag
self.continueflag = Event()
self.continueflag.set()
def run(self):
global runtimes
print ("开始线程:" + self.name)
while self.continueflag.isSet():
if 0 == runtimes:
self.continueflag.clear()
pevent.set()
break
print("I want to consum ... ", runtimes)
pevent.set() #通知生产者要消费
cevent.wait()
cevent.clear()
sleep(1)
print ("退出线程:" + self.name)
self.runflag.set()
def test_pthread():
runflag = Event()
pt = ProducerThread("producer", runflag)
ct = ConsumerThread("consumer", runflag)
pt.start()
ct.start()
pt.join()
ct.join()
runflag.wait()
if __name__ == "__main__":
print("===============begin=================")
test_pthread()
print("===============end=================")运行结果如下:
到此这篇关于python中Event实现线程间同步介绍的文章就介绍到这了,更多相关Event线程间同步内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

