pythoncondition条件变量的作用
1、Python提供的Condition对象支持复杂的线程同步。
2、Condition被称为条件变量,除了提供类似Lock的acquire和release方法外,还提供wait和notify方法。线程先acquire条件变量,然后判断一些条件。
实例
importthreading,time
classHider(threading.Thread):
def__init__(self,cond,name):
super(Hider,self).__init__()
self.cond=cond
self.name=name
defrun(self):
time.sleep(1)#确保先运行Seeker中的方法
self.cond.acquire()#b
print(self.name+':我已经把眼睛蒙上了')
self.cond.notify()
self.cond.wait()#c
#f
print(self.name+':我找到你了~_~')
#self.cond.notify()
self.cond.release()
#g
print(self.name+':我赢了')#h
classSeeker(threading.Thread):
def__init__(self,cond,name):
super(Seeker,self).__init__()
self.cond=cond
self.name=name
defrun(self):
self.cond.acquire()
self.cond.wait()#a#释放对琐的占用,同时线程挂起在这里,直到被notify并重新占有琐。
#d
print(self.name+':我已经藏好了,你快来找我吧')
self.cond.notify()
self.cond.wait()#e
#h
self.cond.release()
print(self.name+':被你找到了,哎~~~')
cond=threading.Condition()
seeker=Seeker(cond,'seeker')
hider=Hider(cond,'hider')
seeker.start()
hider.start()
以上内容为大家介绍了python培训之condition条件变量的作用,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python函数中使用for循环
python函数中使用for循环1、在for循环中使用函数需要更长的执行时间,因为每次迭代都会调用该函数。2、如果for循环是在函数内部实现的,那么该...详情>>
2023-11-14 13:53:34
python3.1版本的特性有哪些
python3.1中的特性有哪些1、千位数格式化,可以在使用字符串格式化函数时直接完成。在格式化大数时,通常是每三位数放置逗号,使数字更易读(例...详情>>
2023-11-14 13:18:27
python__new__()和__init__()有什么区别?
在python中,__new__()不是一定要有,只有继承自object的类才有,该方法可以return父类(通过super(当前类名,cls).__new__())出来的实例,或者直...详情>>
2023-11-14 12:38:55
pythonwheel是什么
python的第一个主流打包格式是.egg文件,现在大家庭中又有了一个叫做Wheel(*.whl)的新成员。wheel“被设计成包含PEP376兼容安装(一种非常接近于...详情>>
2023-11-14 11:30:39热门推荐
pythonSymPy求极值
沸python归并排序和快速排序比较
热pythonpartition如何分割字符串
热pythonif-elif-else语句的使用注意
新python函数中使用for循环
python3.1版本的特性有哪些
python__new__()和__init__()有什么区别?
python作为小白该如何抉择python编辑器?
pythonwheel是什么
python如何定义一个函数
pythonpython是什么类型的语言
python怎么传参数
pythonshell是什么
python如何查看对象属性
技术干货






