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 model.

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

    The asynchronous model allows you to continue the flow during an I / O operation, and to receive a notification when the operation is completed. In this way, the thread can do useful work while I / O is in progress.

    Well, now we have an idea of ​​what it is and therefore decide to use the asynchronous model as the most efficient, but the more we deal with it, the more pitfalls we encounter.

    The difficulties of the asynchronous model are in the creation of understandable, logically consistent code, in the structural mechanism of error handling (now you can forget about try / catch). As a result, we have a large number of hard-to-catch bugs.

    How to deal with it? I will try to state my concepts, which depend on the platform and programming language.

    1) .NET - The easiest and most elegant way, in my opinion, could be implemented by the Microsoft .NET team. Namely, use fibers for 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 the fibers should be carried out by .NET Runtime. It is difficult to realize this on your own, as work with logical threads in .NET Runtime is not documented.
    As a result, the programmer would use a synchronous model and not think about anything, i.e. instead of blocking the flow, the fiber would change to perform another task.

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

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

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

    Also popular now: