使用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()