创新互联Python教程:python中condition条件变量的作用

1、python提供的condition对象支持复杂的线程同步。

目前累计服务客户上千多家,积累了丰富的产品开发及服务经验。以网站设计水平和技术实力,树立企业形象,为客户提供网站制作、成都网站建设、网站策划、网页设计、网络营销、VI设计、网站改版、漏洞修补等服务。创新互联公司始终以务实、诚信为根本,不断创新和提高建站品质,通过对领先技术的掌握、对创意设计的研究、对客户形象的视觉传递、对应用系统的结合,为客户提供更好的一站式互联网解决方案,携手广大客户,共同发展进步。

2、Condition被称为条件变量,除了提供类似Lock的acquire和release方法外,还提供wait和notify方法。线程先acquire条件变量,然后判断一些条件。

实例

import threading, time
class Hider(threading.Thread):
    def __init__(self, cond, name):
        super(Hider, self).__init__()
        self.cond = cond
        self.name = name
    def run(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
class Seeker(threading.Thread):
    def __init__(self, cond, name):
        super(Seeker, self).__init__()
        self.cond = cond
        self.name = name
    def run(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学习指路:创新互联Python教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

新闻名称:创新互联Python教程:python中condition条件变量的作用
网址分享:http://www.hantingmc.com/qtweb/news25/409775.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联