mini-ai/day1/xie.py

54 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import queue
import random
import time
q = queue.Queue(10)
make_num = 3
use_num = 2
speed = 0.8
async def maker():
while True:
while not q.full():
ids = []
# 判断队列中是否有足够的位置供生产
if(q.qsize() > q.maxsize - make_num):
print('× 空间不足')
break
for i in range(make_num):
id = random.randint(1, 100)
q.put(id)
ids.append(id)
time.sleep(speed)
print("+ " + ','.join([str(i) for i in ids]))
print("^ "+ ','.join([str(i) for i in q.queue]))
await user()
async def user():
while True:
while not q.empty():
ids = []
# 判断队列中是否有足够的产品供消费
if(q.qsize() < use_num):
print('× 产品不足')
break
for i in range(use_num):
id = q.get()
ids.append(id)
time.sleep(speed)
print('- ' + ','.join([str(i) for i in ids]))
print("^ "+ ','.join([str(i) for i in q.queue]))
await maker()
async def main():
# 创建并启动两个协程
await asyncio.gather(maker(), user())
if __name__ == '__main__':
asyncio.run(main())