Going asynchronous
Key 3: Being asynchronous for parallel execution.
We can also process more than one request by being asynchronous as well. In this method, instead of us polling for updates from objects, they tell us when they have a result. Hence, the main thread in the meantime can execute other stuff. Asyncio, Twisted, and Tornado are libraries in Python that can help us write such code. Asyncio, and Tornado are supported in Python 3, and some portions of Twisted also run on Python 3 as of now. Python 3.5 introduced the async
and await
keywords that helps write asynchronous code. The async
keyword defines that the function is an asynchronous function and that the result may not be available right away. The await
keyword waits until the results are captured and returns the result.
In the following code, await
in the main function waits for all the results to be available:
import time, asyncio from tasker import cputask, async_iotask from random import randint import aiopg, string, random...