-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoroutines.py
66 lines (44 loc) · 1.05 KB
/
coroutines.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
57
58
59
60
61
62
63
64
65
66
"""
File to demonstrate the coroutines api in python
"""
import asyncio
async def coroutine(caller):
print(f'entering ${caller}')
await asyncio.sleep(1)
print(f'exited {caller}')
"""
asyncio.run takes a coroutine and
A RuntimeWarning is generated if the coroutine is not awaited
Eg: coroutine('without_run')
"""
asyncio.run(coroutine('coroutine_call'))
"""
create_task creates a task which runs a coroutine in the event loop
"""
async def task_runner():
task = asyncio.create_task(coroutine('task_call'))
await task
asyncio.run(task_runner())
print("""
\t\t\tRunning with gather task
""")
async def gather_runner():
"""
asyncio.gather takes in a bunch of coroutines and runs them concurrently
"""
await asyncio.gather(
(coroutine('gather')),
(task_runner()))
asyncio.run(gather_runner())
"""
OUTPUT:
entering $coroutine_call
exited coroutine_call
entering $task_call
exited task_call
Running with gather task
entering $gather
entering $task_call
exited gather
exited task_call
"""