码迷,mamicode.com
首页 > 编程语言 > 详细

python多线程之Condition(条件变量)

时间:2016-11-23 10:11:48      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:str   lease   print   rod   技术   []   notify   __init__   consumer   

#!/usr/bin/env python
# -*- coding: utf-8 -*-


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()
        if len(items) == 0:
            condition.wait()
            print ("Consumer notify: no item to consume")
        items.pop()
        print("Consumer notify: consumed 1 item")
        print("Consumer nofity: items to consume are "              + str(len(items)))
        condition.notify()
        condition.release()

    def run(self):
        for i in range(0, 20):
            time.sleep(4)
            self.consume()

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

    def produce(self):
        global condition
        global items

        condition.acquire()
        if len(items) == 10:
            condition.wait()
            print ("Producer notify: item producted are"                   + str(len(items)))
            print("Producer nofity: stop the production!!")
        items.append(1)
        print("Producer nofity: total items producted "              + str(len(items)))
        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()
    
        

技术分享

python多线程之Condition(条件变量)

标签:str   lease   print   rod   技术   []   notify   __init__   consumer   

原文地址:http://www.cnblogs.com/aguncn/p/6092549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!