使用condition的方式实现生产者与消费者

一、创建生产者与消费者具体代码

import time
import threading
import random

# 定义仓库里面多少包子
gBum = 10
# 总共生产多少次
gTotalTimes = 10
# 定义当前的
gTimes = 0

gCondition = threading.Condition()

class Producer(threading.Thread):
    """
    创建一个生产者
    """

    def run(self):
        global gBum
        global gTotalTimes
        global gTimes

        while True:
            bum = random.randint(0, 10)
            gCondition.acquire()
            if gTimes >= gTotalTimes:
                gCondition.release()
                print('当前生产者总共生产了{0}次'.format(gTimes))
                break
            gBum += bum
            print('{0}生产了:{1}个包子,还剩余:{2}个包子'.format(threading.current_thread(), bum, gBum))
            gTimes += 1
            time.sleep(random.randrange(3))
            # 发出信号
            gCondition.notify_all()
            # 释放锁
            gCondition.release()

class Consumer(threading.Thread):
    """
    定义一个消费者类
    """

    def run(self):
        global gBum
        global gTotalTimes
        global gTimes

        while True:
            bum = random.randint(0, 10)
            gCondition.acquire()
            while gBum < bum:
                if gTimes >= gTotalTimes:
                    gCondition.release()
                    return
                print("{0}在消费包子,消费了{1}个,但是包子数量不够,还剩余{2}".format(threading.current_thread(), bum, gBum))
                gCondition.wait()

            gBum -= bum
            print("{0}在消费包子,消费了{1}个,还剩余{2}".format(threading.current_thread(), bum, gBum))
            time.sleep(random.randrange(4))
            gCondition.release()

if __name__ == '__main__':
    # # 启动八个消费者线程
    for x in range(8):
        t = Consumer(name='消费者线程%d' % x)
        t.start()

    # 启动三个生产者
    for x in range(3):
        t = Producer(name='生产者%d' % x)
        t.start()

results matching ""

    No results matching ""