forked from calebmadrigal/asyncio-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
call_sync_code.py
44 lines (33 loc) · 1.03 KB
/
call_sync_code.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
"""
Demonstrate use of concurrent.futures.ThreadPoolExecutor (default executor: None, already in the event loop)
to bring good asynchronous behaviour to a non-asyncio, blocking function.
Show how each task is 'gathered' until completion.
@jorjun Dies Martis, Sol in Leo, Luna in Gemini, An:Viv
"""
import asyncio
import time
from urllib.request import urlopen
from functools import partial
def blocking_get_page_len(url):
time.sleep(2) # This is the blocking sleep (not the async-friendly one)
page = urlopen(url).read()
return len(page)
async def task_count_to_10():
for i in range(11):
print(f"Counter: {i}")
await asyncio.sleep(.5)
async def task_print_data_size():
data = await loop.run_in_executor(
None, partial(blocking_get_page_len, url="http://calebmadrigal.com")
)
print(f"Data size: {data}")
loop = asyncio.get_event_loop()
loop.set_debug(True)
tasks = [
task_count_to_10(),
task_print_data_size()
]
loop.run_until_complete(
asyncio.gather(*tasks)
)
loop.close()