• 技术文章 >Python技术 >Python基础教程

    python中condition条件变量的作用

    小妮浅浅小妮浅浅2021-11-03 10:15:27原创30940

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

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

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    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 condition
    上一篇:python列表推导式的结构探究 下一篇:python单元测试中的函数整理

    相关文章推荐

    • python异常处理的作用• python ndarray数组对象有什么特点• python函数中使用for循环• python变量赋值的注意点• python执行数据库的查询操作• python元类冲突的问题• python os.system执行cmd指令• python os.popen方法是什么• python中subprocess的用法• 如何走进Python的大门?• python蒙特卡洛算法的介绍• python如何过滤列表中的唯一值• python列表推导式的结构探究

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网