import asyncio
import functools
import random
import time
def
notifier(
cond,
t):
''' set event '''
t2=time.time()-t
print(
'set_event (
%5.3f
) :trigger the event...'%t2)
cond.notify_all()
t2=time.time()-t
print(
'set_event (
%5.3f
) :trigger triggerred..'%t2)
async
def
worker(
cond,
name,
t):
''' task '''
t2 = time.time() - t
print(
'worker (
%s
)(
%5.3f
) :start task' % (name, t2))
print(
'worker (
%s
)(
%5.3f
) :working for some seconds' % (name, t2))
await asyncio.sleep(random.random() *
3 +
2)
t2 = time.time() - t
print(
'worker (
%s
)(
%5.3f
) :afterwork,waiting for trigger' % (name, t2))
with
await cond:
#此部分是被锁住的,看下面的执行时间就看出来了
await cond.wait()
t2 = time.time() - t
print(
'worker (
%s
)(
%5.3f
) :trigger was touched,i will do something.' % (name, t2))
await asyncio.sleep(random.random() *
3 +
2)
t2 = time.time() - t
print(
'worker (
%s
)(
%5.3f
) :my task is done.' % (name, t2))
async
def
officer(
cond,
t):
'''officer'''
await asyncio.sleep(
6.5)
with
await cond:
notifier(cond,t)
async
def
main(
loop):
'''main'''
cond=asyncio.Condition()
t1=time.time()
task=loop.create_task(officer(cond,t1))
workers=[worker(cond,i,t1)
for i
in
range(
3)]
await asyncio.wait(workers)
task.cancel()
loop=asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
----------------------------------------------------------------------
worker (2)(0.000) :start task
worker (2)(0.000) :working for some seconds
worker (1)(0.001) :start task
worker (1)(0.001) :working for some seconds
worker (0)(0.001) :start task
worker (0)(0.001) :working for some seconds
worker (0)(2.295) :afterwork,waiting for trigger
worker (2)(4.149) :afterwork,waiting for trigger
worker (1)(4.264) :afterwork,waiting for trigger
set_event (6.506) :trigger the event...
set_event (6.506) :trigger triggerred..
worker (0)(6.507) :trigger was touched,i will do something.
worker (0)(8.748) :my task is done.
worker (2)(8.748) :trigger was touched,i will do something.
worker (2)(11.899) :my task is done.
worker (1)(11.899) :trigger was touched,i will do something.
worker (1)(15.157) :my task is done.
worker (2)(0.000) :working for some seconds
worker (1)(0.001) :start task
worker (1)(0.001) :working for some seconds
worker (0)(0.001) :start task
worker (0)(0.001) :working for some seconds
worker (0)(2.295) :afterwork,waiting for trigger
worker (2)(4.149) :afterwork,waiting for trigger
worker (1)(4.264) :afterwork,waiting for trigger
set_event (6.506) :trigger the event...
set_event (6.506) :trigger triggerred..
worker (0)(6.507) :trigger was touched,i will do something.
worker (0)(8.748) :my task is done.
worker (2)(8.748) :trigger was touched,i will do something.
worker (2)(11.899) :my task is done.
worker (1)(11.899) :trigger was touched,i will do something.
worker (1)(15.157) :my task is done.