How to do it...

The following example shows how to use the asyncio.Future class for the management of two coroutines: first_coroutine and second_coroutine, which perform the following tasks. first_coroutine performs the sum of the first N integers, and second_coroutine performs the factorial of N:

  1. Now, let's import the relevant libraries:
import asyncio
import sys
  1. first_coroutine implements the sum function of the first N integers:
@asyncio.coroutine
def first_coroutine(future, num):
count = 0
for i in range(1, num + 1):
count += i
yield from asyncio.sleep(1)
future.set_result('First coroutine (sum of N integers)
result = %s' % count)
  1. In second_coroutine, we still implement the factorial function:
@asyncio.coroutine
def second_coroutine(future, num):
count = 1
for i in range(2, num + 1):
count *= i
yield from asyncio.sleep(2)
future.set_result('Second coroutine (factorial) result = %s' %
count)
  1. Using the got_result function, we print the output of the computation:
def got_result(future):
print(future.result())
  1. In the main function, the num1 and num2 parameters must be set by the user. They will be used as parameters for the functions implemented by the first and second coroutines:
if __name__ == "__main__":
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

  1. Now, let's take the event loop:
    loop = asyncio.get_event_loop()
  1. Here, the futures are defined by the asyncio.future function:
    future1 = asyncio.Future()
future2 = asyncio.Future()
  1. The two coroutines—first_couroutine and second_couroutine—included in the tasks list have the future1 and future2 futures, the user-defined arguments, and the num1 and num2 parameters:
tasks = [first_coroutine(future1, num1),
second_coroutine(future2, num2)]
  1. The futures have added a callback:
    future1.add_done_callback(got_result)
future2.add_done_callback(got_result)
  1. Then, the tasks list is added to the event loop, so that the computation can begin:
    loop.run_until_complete(asyncio.wait(tasks))
loop.close()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset