W
W
WebDev2020-05-24 15:41:20
Node.js
WebDev, 2020-05-24 15:41:20

A question about multithreading and the work of processor cores and nodejs?

Hello!
Please help me to clarify and understand exactly how a modern multi-core processor works.
Let's say there is a script that runs on the server. Before, when the processor had one core, everything was clear - the processor processes the script in one thread sequentially.
Then multi-core processors appeared, which can parallelize and simultaneously execute several scripts (each core, independently of the others, can execute something).
Immediately there appeared programming languages ​​and tools that can work with multithreading. If you imagine very roughly, then the work consists in the ability to "distribute" tasks to several cores, and then collect the result of the work of each core and "glue" it into the final result. For example, if a script consists of four complex calculations, each of which takes 1 second, then a single-core processor would perform these calculations in turn and would spend 4 seconds in total. And a quad-core processor will take one calculation for each core, perform all 4 calculations in 1 second in parallel, and return the result in 1 second. Well, this is a very rough idea.
With this, everything is more or less clear. But above it was about the ability of the PL to use the processor cores at the discretion of the programmer who writes the program. And how will work work in the following case:
I am writing a script on nodejs + websocket. This will be an online chat. One person writes a message, another receives it, and so on. Will all processor cores be used in this case? If so, how? Does Nodejs run out of the box and use all cores?
If I draw an analogy with PHP (and, unfortunately, I haven’t worked with anything else yet), then in PHP the script “runs” and “dies” every time. He has no state. A request came from a user - the script started, connected to the database, wrote something there and died. Therefore, each new request can take on a different core. And in nodejs there is this very "state". That is, the program is running and the data is the same for everyone.

let users: [];
let messages: [];

ws.on('connection', socket=> {
    users.push(socket);
  
    socket.on('message', message => {
        messages.push(message);

        users.forEach(user => user.emit('message', message));
    });
});


How in this case requests will be processed in parallel? After all, they work with the same data.
Explain, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2020-05-24
@firedragon

https://nodejs.org/api/worker_threads.html For good reason, the node evenly distributes tasks across the cores. But your task is to use it wisely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question