1. 功能需求
- 由生产者进行生产
- 由消费者进行消费
- 消费者消费金额不能大于余额
- 生产10次以后不再生产
- 当余额小于消费金额且生产次数达到10次后,就不再消费
2. Lock版生产者和消费者
import threading
import random
import time
gMoney = 0
gTimes = 0
gLock = threading.Lock()
class Producer(threading.Thread):
def run(self) -> None:
global gMoney
global gTimes
while True:
gLock.acquire()
if gTimes >= 10:
gLock.release()
break
money = random.randint(0, 100)
gMoney += money
gTimes += 1
print('%s生产了%d元钱' % (threading.current_thread().name, money))
gLock.release()
time.sleep(1)
class Consumer(threading.Thread):
def run(self) -> None:
global gMoney
while True:
gLock.acquire()
money = random.randint(0, 100)
if gMoney >= money:
gMoney -= money
print('%s消费了%d元钱' % (threading.current_thread().name,money))
else:
if gTimes >= 10:
gLock.release()
break
print('%s消费了%d元钱,但余额为%d,余额不足' % (threading.current_thread().name,money,gMoney))
gLock.release()
time.sleep(1)
def main():
for i in range(5):
th = Producer(name='生产者%d号' % i)
th.start()
for i in range(5):
th = Consumer(name='消费者%d号' % i)
th.start()
if __name__ == '__main__':
main()
3. Condition版生产者和消费者
import threading
import random
import time
gMoney = 0
gTimes = 0
gCond = threading.Condition()
class Producer(threading.Thread):
def run(self) -> None:
global gMoney
global gTimes
while True:
gCond.acquire()
if gTimes >= 10:
gCond.release()
break
money = random.randint(0, 100)
gMoney += money
gTimes += 1
print('%s生产了%d元钱,剩余%d元' % (threading.current_thread().name, money,gMoney))
gCond.notifyAll()
gCond.release()
time.sleep(1)
class Consumer(threading.Thread):
def run(self) -> None:
global gMoney
while True:
gCond.acquire()
money = random.randint(0, 100)
while money >= gMoney:
if gTimes >= 10:
gCond.release()
return
print('%s消费了%d元钱,但是余额为%d元钱,生产者也不再生成了' % (threading.current_thread().name, money,gMoney))
gCond.wait()
gMoney -= money
print('%s消费了%d元钱,剩余%d元' % (threading.current_thread().name, money,gMoney))
gCond.release()
time.sleep(1)
def main():
for i in range(5):
th = Producer(name='生产者%d号' % i)
th.start()
for i in range(5):
th = Consumer(name='消费者%d号' % i)
th.start()
if __name__ == '__main__':
main()