-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsync_code_example.py
More file actions
48 lines (35 loc) · 1.12 KB
/
Async_code_example.py
File metadata and controls
48 lines (35 loc) · 1.12 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
47
48
# Async code
# Async runs in the same thread
# Async uses Coroutines which run on the same thread
# We also introduce the async and await keywords
import random
import threading
import multiprocessing
import logging
import asyncio
logging.basicConfig(format='%(levelname)s - %(asctime)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG)
def display(msg):
threadname = threading.current_thread().name
processname = multiprocessing.current_process().name
logging.info(f'{processname}\{threadname}:{msg}')
async def work(name):
display(name + 'starting')
# Without await it will jump to next line
await asyncio.sleep(random.randint(1, 10))
display(name + 'finished')
async def run_async(max):
tasks = []
for x in range(max):
name = "Item" + str(x)
tasks.append(asyncio.ensure_future(work(name)))
await asyncio.gather(*tasks)
def main():
display('Main Started')
loop = asyncio.get_event_loop()
loop.run_until_complete(run_async(50))
# Run forever
# loop.run_forever()
loop.close()
display('Main Finished')
if __name__ == '__main__':
main()