forked from your-tools/python-cli-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasynchronous.py
More file actions
46 lines (35 loc) · 1.06 KB
/
Copy pathasynchronous.py
File metadata and controls
46 lines (35 loc) · 1.06 KB
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
import asyncio
import cli_ui
async def long_computation():
# Simulates a long computation
await asyncio.sleep(0.6)
async def count_down(lock, start):
x = start
while x >= 0:
async with lock:
# Note: the sleeps are here so that we are more likely to
# see mangled output
#
# In reality, if you only call `ui.info()` once you don't
# need locks at all thanks to the GIL
cli_ui.info("down", end=" ")
await asyncio.sleep(0.2)
cli_ui.info(x)
await asyncio.sleep(0.2)
await long_computation()
x -= 1
async def count_up(lock, stop):
x = 0
while x <= stop:
async with lock:
cli_ui.info("up", end=" ")
await asyncio.sleep(0.2)
cli_ui.info(x)
await asyncio.sleep(0.2)
await long_computation()
x += 1
async def main():
lock = asyncio.Lock()
await asyncio.gather(count_down(lock, 4), count_up(lock, 4))
if __name__ == "__main__":
asyncio.run(main())