python 生产者-消费者模型

时间:2022-09-20 17:40:57

代码示例

#!/usr/bin/env python
#encoding: utf-8
import threading
import time

condition = threading.Condition()
products = 0

class Producer(threading.Thread):
    def run(self):
        global products
        while True:
            if condition.acquire():
                if products < 10:
                    products += 1
                    print("Producer(%s):deliver one, now products have:%s" % (self.name, products))
                    condition.notify()
                    condition.release()
                else:
                    print("Producer(%s):the products have 10, stop produce, now products have:%s" % (self.name, products))
                    condition.wait()
                time.sleep(3)


class Consumer(threading.Thread):
    def run(self):
        global products
        while True:
            if condition.acquire():
                if products > 0:
                    products -= 1
                    print("Consumer(%s):consume one, now products have:%s" % (self.name, products))
                    condition.notify()
                    condition.release()
                else:
                    print("Consumer(%s):the products is selling out, stop consume,now products have:%s" % (self.name, products))
                    condition.wait()
                time.sleep(3)


if __name__ == "__main__":
    for p in range(0, 4):
        p = Producer()
        p.start()

    for c in range(0, 5):
        c = Consumer()
        c.start()