How does asynchronous programming work in a single-processor programming model?

I went through the details of node.js and found out that it supports asynchronous programming, although in essence it provides one threading model.

How is asynchronous programming handled in such cases? It looks like the runtime itself creates and manages threads, but the programmer cannot create threads explicitly? It would be great if someone could point me to some resources to find out about this.

+53
asynchronous
Jan 24 2018-12-12T00:
source share
2 answers

Tell me now: asynchronous programming does not necessarily mean multithreading.

Javascript is a single-threaded runtime - you simply cannot create new threads in JS because the language / runtime does not support it.

Frank says it right (albeit stupidly). In English: there is a main event loop that processes when something comes into your application. Thus, “process this HTTP request” will be added to the event queue and then processed by the event loop when necessary.

When you invoke an async operation (for example, mysql db query), node.js sends “hey, execute this request” to mysql. Since this request will take some time (milliseconds), node.js executes the request using the MySQL async library - it returns to the event loop and does something else there, waiting for mysql to return to us. Similar to handling this HTTP request.

Change In contrast, node.js can just wait (do nothing) for mysql to return to it. This is called a synchronous call. Imagine a restaurant where your waiter submits your order to a cook, then sits down and squeezes his thumbs while the chef cooks. In a restaurant, as in the node.js program, this behavior is stupid - you have other clients who are hungry and in need of service. Thus, you want to be as asynchronous as possible to make sure that one waiter (or node.js process) serves as many people as possible.

Edited done

Node.js communicates with mysql using the C libraries, so technically these C libraries can come from threads, but inside Javascript you can't do anything with threads.

+70
Jan 24 2018-12-12T00:
source share

Ryan said the best: sync / async is orthogonal to single / multi-threaded. For single-threaded and multi-threaded cases, there is a main event loop that calls registered callbacks using the Reactor Pattern . For the single-threaded case, callbacks are invoked sequentially in the main thread. For the multi-threaded case, they are called in separate threads (usually using a thread pool). Actually, the question is how much competition there will be: if all requests require synchronized access to a single data structure (say, a list of subscribers), the benefits of having multiple threads can be reduced. It depends on the problem.

As for the implementation, if the structure is single-threaded, then it probably uses the poll / select system call, that is, the OS fires an asynchronous event.

+8
Jan 24 2018-12-12T00:
source share



All Articles