-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathasyncio_tasks.py
63 lines (42 loc) · 1.38 KB
/
asyncio_tasks.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
# Code Listing #12
"""
Example of co-operative multitasking using asyncio
"""
import asyncio
def number_generator(m, n):
""" A number generator co-routine in range(m...n+1) """
yield from range(m, n+1)
async def prime_filter(m, n):
""" Prime number co-routine """
primes = []
for i in number_generator(m, n):
if i % 2 == 0: continue
flag = True
for j in range(3, int(i**0.5+1), 2):
if i % j == 0:
flag = False
break
if flag:
print('Prime=>',i)
primes.append(i)
# At this point the co-routine suspends execution
# so that another co-routine can be scheduled.
await asyncio.sleep(1.0)
return tuple(primes)
async def square_mapper(m, n):
""" Square mapper co-routine """
squares = []
for i in number_generator(m, n):
print('Square=>',i*i)
squares.append(i*i)
# At this point the co-routine suspends execution
# so that another co-routine can be scheduled.
await asyncio.sleep(1.0)
return squares
def print_result(future):
print('Result=>',future.result())
loop = asyncio.get_event_loop()
future = asyncio.gather(prime_filter(10, 50), square_mapper(10, 50))
future.add_done_callback(print_result)
loop.run_until_complete(future)
loop.close()