这篇文章主要介绍“python中Event怎么实现线程间同步”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“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怎么实现线程间同步”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。