📜 ⬆️ ⬇️

Asynchronous programming model (part 1)

To begin with, we will deal with the problem, namely, why do we need an asynchronous model and what does not suit the synchronous one?

The synchronous model blocks the stream, waiting for the result of the input / output (network, file system, etc., then I / O), therefore a separate stream is needed to perform something else. Thus, the bottleneck of this model is threads and context switching of threads, which is a very resource-intensive operation.
Ideally, there is no need for the system to have as many worker threads as there are processors (cores) in the system.

The asynchronous model allows you to continue executing the stream during an I / O operation, and receive a notification when the operation completes. Thus, a thread can perform useful work while an I / O is being performed.
')
Great, now we have an idea of ​​what it is and therefore we decide to use the asynchronous model as the most efficient, but the more we deal with it, the more reefs we encounter.

The difficulties of the asynchronous model consist in the creation of a clear, coherent code, in the structural mechanism of error handling (because now you can forget about try / catch). As a result, we have a large number of difficult to catch bugs.

How to deal with it? I will try to explain my concepts that depend on the platform and programming language.

1) .NET - The easiest and most elegant way, in my opinion, could be implemented by the .NET Microsoft team. Namely, use fibers for the logical flows in .NET. Fibers are lightweight objects that could execute code, switching between them is not resource intensive. The control of the number of system threads as well as switching between fibers should be done by the .NET Runtime. Implement it yourself is difficult, because The work with logical threads in .NET Runtime is not documented.
As a result, the programmer would use the synchronous model and did not think about anything, i.e. instead of blocking the flow, there would be a fiber change to perform another task.

2) C # .NET - Implement a mechanism, a pattern in which the asynchronous model would also have the advantages of a synchronous model - a logical sequential code, a mechanism for structural error handling. This approach with code examples will be described in the next section.

3) C ++ / Windows - This approach is practically described in paragraph 1, i.e. fibers must be used to support the asynchronous model.

I described it briefly, I hope it is clear and useful.
This is my first article on Habré, do not judge strictly;)

Source: https://habr.com/ru/post/69205/


All Articles