python多线程Condition代码示例

# -*- coding:utf-8 -*-
import threading
import time
class Producer(threading.Thread):
    # 生产者函数,重写run()方法
    def run(self):
        global count
        while True:
            if con.acquire():
                # 当count 小于等于1000 的时候进行生产
                if count > 1000:
                    # 当库存已经超过1000,则线程阻塞,等待其它线程notify()
                    con.wait()
                else:
                    count = count+100
                    msg = self.name+' produce 100, count=' + str(count)
                    print(msg)
                    # 完成生成后唤醒waiting状态的线程,
                    # 从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁
                    con.notify()
                # 释放acquire()占有的锁
                con.release()
                time.sleep(2)

class Consumer(threading.Thread):
    # 消费者函数,重写run()方法
    def run(self):
        global count
        while True:
            # 当count 大于0的时候进行消费
            if con.acquire():
                if count > 0:
                    count = count-50
                    msg = self.name+' consume 50, count='+str(count)
                    print(msg)
                    # 完成消费后唤醒waiting状态的线程,
                    # 从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁
                    con.notify()                
                else:
                    # 当库存已经没有,则线程阻塞,等待其它线程notify()
                    con.wait()
                # 释放acquire()占有的锁
                con.release()
                time.sleep(2)

count = 0
con = threading.Condition()

def main():
    # 1生产者线程,3个消费者线程
    p = Producer()
    p.start()
    for i in range(3):
        c = Consumer()
        c.start()
if __name__ == '__main__':
    main()

 

posted @ 2022-02-10 14:32  荒野游侠  阅读(128)  评论(0编辑  收藏  举报