Python并行编程(六):线程同步之条件

1、基本概念

      条件指的是应用程序状态的改变。其中某些线程在等待某一条件发生,其 他线程会在该条件发生的时候进行通知,一旦条件发生,线程会拿到共享资源的唯一权限。

2、示例代码

from threading import Thread, Condition
import time

items = []
condition = Condition()

class consumer(Thread):

    def __init__(self):
        Thread.__init__(self)

    def consume(self):
        global condition
        global items
# 消费者通过condition.acquire得到锁来修改共享资源items condition.acquire()
if len(items) == 0:
# 如果list长度为0,那么消费者就进入等待状态 condition.wait()
print("Consumer notify: no item to consume") # 不为零通过pop消费一个item items.pop() print("Consumer notify: consumed 1 item") print("Consumer notify: items to conseme are %s" %str(len(items))) # 然后消费者的状态被通知给生产者,同时共享资源释放。 condition.notify() condition.release() def run(self): for i in range(0, 20): time.sleep(2) self.consume() class producer(Thread): def __init__(self): Thread.__init__(self) def produce(self): global condition global items
# 生产获得锁,查看缓冲队列是否已满,本例为10个,如果满了,就进入等待状态,直到被唤醒。 condition.acquire()
if len(items) == 10: condition.wait() print("Producer notify: items producted are %s" %str(len(items))) print("Producer notify: stop the production!!") items.append(1) print("Producer notify: total items producted %s" %str(len(items)))
# 如果队列没有满,就生产一个item,通知状态并释放资源 condition.notify() condition.release()
def run(self): for i in range(0, 20): time.sleep(1) self.produce() if __name__ == "__main__": producer = producer() consumer = consumer() producer.start() consumer.start() producer.join() consumer.join()

      执行结果如下:

      

原文地址:https://www.cnblogs.com/dukuan/p/9773548.html