How it works...

In the main program, we define the future objects, future1 and future2 respectively, using via the asyncio.Future() directive:

if __name__ == "__main__":
future1 = asyncio.Future()
future2 = asyncio.Future()

In defining the tasks, we pass the future objects as an argument of the two coroutines first_couroutine and second_couroutine:

tasks = [first_coroutine(future1,num1), 
second_coroutine(future2,num2)]

Finally, we add a callback to be run when future is done:

future1.add_done_callback(got_result)
future2.add_done_callback(got_result)

Here, got_result is a function that prints the result of future:

def got_result(future):
print(future.result())

In the coroutine, we pass the future object as an argument. After the computation, we set sleep times of 3 seconds for the first coroutine and 4 seconds for the second one:

yield from asyncio.sleep(sleep_time)

The following output is obtained by executing the command with different values:

> python asyncio_and_futures.py 1 1
First coroutine (sum of N integers) result = 1
Second coroutine (factorial) result = 1


> python asyncio_and_futures.py 2 2
First coroutine (sum of N integers) result = 2
Second coroutine (factorial) result = 2

> python asyncio_and_futures.py 3 3
First coroutine (sum of N integers) result = 6
Second coroutine (factorial) result = 6


> python asyncio_and_futures.py 5 5
First coroutine (sum of N integers) result = 15
Second coroutine (factorial) result = 120


> python asyncio_and_futures.py 50 50
First coroutine (sum of N integers) result = 1275
Second coroutine (factorial) result = 30414093201713378043612608166064768844377641568960512000000000000
First coroutine (sum of N integers) result = 1275

..................Content has been hidden....................

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