Asynchronous Programming

Beside the sequential and parallel execution models, there is a third model that is of fundamental importance together with the concept of event programming: the asynchronous model.

The execution model of asynchronous tasks can be implemented through a single main control flow, both in single-processor systems and in multiprocessor systems. In the concurrent asynchronous execution model, the executions of various tasks intersect along the timeline, and everything happens under the action of a single flow of control (single-threaded). Once started, the execution of tasks can be suspended and then resumed over time, alternating with the execution of other current tasks that are present.

The development of code for the asynchronous model is completely different from that for multithreaded programming. A substantial difference between the concurrent multithreaded parallel model and the single-threaded concurrent asynchronous model lies in the fact that, in the first case, the OS decides on the timeline if we suspend the activity of one thread and start another.

This remains outside the control of the coder, unlike the asynchronous model. The execution or termination of a task continues as long as it is explicitly required.

The most important feature of this type of programming is that the code is not performed on multiple threads, as in the classic concurrent programming, but on a single thread. Thus, it is not at all true that two tasks are executed at the same time, but, according to this approach, they are performed at almost the same time.

In particular, we will describe the asyncio Python module, which was introduced in Python 3.4. This allows us to use coroutines and futures to make writing asynchronous code easier and to make it more readable.

In this chapter, we will cover the following recipes:

  • Using the concurrent.futures Python module
  • Managing the event loop with asyncio
  • Handling coroutines with asyncio
  • Manipulating tasks with asyncio
  • Dealing with asyncio and futures
..................Content has been hidden....................

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