import asyncio
import functools
import random
import time
async def worker(q,name,event,t):
''' worker'''
t2 = time.time() - t
print(f'worker {name:03d} :{t2:6.3f} waiting for working')
while True:
r=await q.get()
t2=time.time()-t
if r >= 100:
#测试结束标志:如果是300 就通知 main 结束任务
print(f'worker {name:03d} :{t2:6.3f} my work all done!')
if r==300:
event.set()
else:
await q.put(r+100)
return
else:
print(f'worker {name:03d} :{t2:6.3f} get work and do it')
await asyncio.sleep(random.random() * 3 + 1)
t3 = time.time() - t
print(f'worker {name:03d} :{t3:6.3f} work is done,and result is {r}')
async def officer(q,t):
t2=time.time()-t
print(f'officer :{t2:6.3f} distribute work.')
for i in range(10):
await asyncio.sleep(random.random() * 1 + 1)
await q.put(i)
t2=time.time()-t
print(f'officer :{t2:6.3f} added a work ')
await q.put(100)
async def main(loop):
q = asyncio.Queue()
event=asyncio.Event()
t1=time.time()
task = loop.create_task(asyncio.wait([worker(q,_+1,event,t1) for _ in range(3)]))
await officer(q,t1)
await event.wait()
task.cancel()
t2=time.time()-t1
print(f'main :{t2:6.3f} over')
officer : 0.000 distribute work.
worker 001 : 0.001 waiting for working
worker 002 : 0.001 waiting for working
worker 003 : 0.001 waiting for working
officer : 1.636 added a work
worker 001 : 1.636 get work and do it
officer : 3.423 added a work
worker 002 : 3.423 get work and do it
worker 001 : 4.011 work is done,and result is 0
worker 002 : 5.371 work is done,and result is 1
officer : 5.371 added a work
worker 003 : 5.372 get work and do it
officer : 6.762 added a work
worker 001 : 6.762 get work and do it
worker 003 : 6.923 work is done,and result is 2
officer : 8.468 added a work
worker 001 : 8.469 work is done,and result is 3
worker 001 : 8.470 get work and do it
officer : 9.486 added a work
worker 003 : 9.486 get work and do it
worker 001 :10.201 work is done,and result is 4
officer :11.150 added a work
worker 002 :11.152 get work and do it
worker 002 :12.517 work is done,and result is 6
officer :12.877 added a work
worker 001 :12.877 get work and do it
worker 003 :13.220 work is done,and result is 5
officer :14.533 added a work
worker 002 :14.533 get work and do it
officer :15.810 added a work
worker 003 :15.810 get work and do it
worker 001 :15.902 work is done,and result is 7
worker 001 :15.902 my work all done!
worker 002 :17.771 work is done,and result is 8
worker 002 :17.773 my work all done!
worker 003 :18.579 work is done,and result is 9
worker 003 :18.579 my work all done!
main :18.580 over