-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_condition.py
56 lines (38 loc) · 1.15 KB
/
async_condition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
some_counter = 0
async def cwait(c: asyncio.Condition, m: str):
async with c:
await c.wait()
print("waited: ", m)
async def counter(n: int):
nstart = n
for i in range(n):
await asyncio.sleep(1)
print("counter: ", nstart - i)
async def inc_some_counter():
global some_counter
while True:
some_counter += 1
await asyncio.sleep(0.001)
async def wait_come_counter(c: asyncio.Condition, value):
async with c:
await c.wait_for(lambda: some_counter > value)
print("finished waiting for:", value, " actual: ", some_counter)
async def main():
c = asyncio.Condition()
asyncio.create_task(inc_some_counter())
asyncio.create_task(wait_come_counter(c, 100))
asyncio.create_task(wait_come_counter(c, 1000))
for i in range(10):
asyncio.create_task(cwait(c, str(i+1)))
print("started condition wait tasks...")
await counter(1)
async with c:
c.notify(5)
print("notified 5 of them...")
await counter(5)
async with c:
c.notify_all()
print("notified the rest...")
await counter(5)
asyncio.run(main())