Python多线程之Condition条件变量

2019-11-24  本文已影响0人  老苏GO

Condition对象

1.基本介绍

此对象为Python中的threading模块中的Condition类. 称之为条件变量. 此对象的主要用途是应对线程同步问题. 首先我们先来看看条件变量的概念.

条件变量:

2.应用场景

线程A需要等某个条件才能继续往下执行, 条件不成立, 线程A阻塞等待, 当线程B执行过程中更改条件使之对线程A成立, 就唤醒线程A继续执行.

3.对象基本方法

4.生产者消费者示例

# -*- coding: utf-8 -*-
import threading
import random
import time


class Producer(threading.Thread):

    def __init__(self, integers, condition):
        threading.Thread.__init__(self)
        self.integers = integers
        self.condition = condition

    def run(self):
        while True:
            integer = random.randint(0, 256)
            self.condition.acquire()
            print("condition acquired by {}".format(self.name))

            self.integers.append(integer)
            print("{} appended to list by {}".format(integer, self.name))

            print("condition notified by {}".format(self.name))
            self.condition.notify()

            print("condition released by {}".format(self.name))
            self.condition.release()
            time.sleep(1)


class Consumer(threading.Thread):

    def __init__(self, integers, condition):
        threading.Thread.__init__(self)
        self.integers = integers
        self.condition = condition

    def run(self):
        while True:
            self.condition.acquire()
            print("condition acquired by {}".format(self.name))

            while True:
                if self.integers:
                    integer = self.integers.pop()
                    print("{} popped from list by {}".format(integer, self.name))
                    break
                print("condition wait by {}".format(self.name))
                self.condition.wait()

                print("condition released by {}".format(self.name))
                self.condition.release()


def main():
    integers = []
    condition = threading.Condition()
    t1 = Producer(integers, condition)
    t2 = Consumer(integers, condition)
    t1.start()
    t2.start()
    t1.join()
    t2.join()


if __name__ == '__main__':
    main()

引用

上一篇 下一篇

猜你喜欢

热点阅读