forked from lancelote/parallel_python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasyncio_task_manipulation.py
42 lines (33 loc) · 1.19 KB
/
asyncio_task_manipulation.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
"""Asyncio using Asyncio.Task to execute three math functions in parallel"""
import asyncio
@asyncio.coroutine
def factorial(number):
fact = 1
for i in range(2, number + 1):
print('Asyncio.Task: Compute factorial(%s)' % i)
yield from asyncio.sleep(1)
fact *= i
print('Asyncio.Task - factorial(%s) = %s' % (number, fact))
@asyncio.coroutine
def fibonacci(number):
a, b = 0, 1
for i in range(number):
print('Asyncio.Task: Compute fibonacci(%s)' % i)
yield from asyncio.sleep(1)
a, b = b, a + b
print('Asyncio.Task - fibonacci(%s) = %s' % (number, a))
@asyncio.coroutine
def binomial_coefficient(n, k):
result = 1
for i in range(1, k + 1):
result = result*(n - i + 1)/i
print('Asyncio.Task: Compute binomial_coefficient(%s)' % i)
yield from asyncio.sleep(1)
print('Asyncio.Task - binomial_coefficient(%s, %s) = %s' % (n, k, result))
if __name__ == '__main__':
tasks = [asyncio.Task(factorial(10)),
asyncio.Task(fibonacci(10)),
asyncio.Task(binomial_coefficient(20, 10))]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()