0

I have a question, Node.js uses libuv inside of u core, to manage its event loop and by default works whit 4 threads and process queue whit limit of 1024 process.

Process queue limit

Threads by default

So, because most programmers say it's single thread?

Hume
  • 389
  • 5
  • 15
  • 2
    Does this answer your question? [How the single threaded non blocking IO model works in Node.js](https://stackoverflow.com/questions/14795145/how-the-single-threaded-non-blocking-io-model-works-in-node-js) – Joe Nov 07 '19 at 03:18

1 Answers1

1

By default, node.js only uses ONE thread to run your Javascript. Thus your Javascript runs as single threaded. No two pieces of your Javascript are ever running at the same time. This is a critical design element in Javascript and is why it does not generally have concurrency problems with access to shared variables.

The event driven system works by doing this:

  1. Fetch event from event queue.
  2. Run the Javascript callback associated with the event.
  3. Run that Javascript until it returns control back to the system.
  4. Fetch the next event from the event queue and go back to step 2.
  5. If no event in the event queue, go to sleep until an event is added to the queue, then go to step 1.

In this way, you can see that a given piece of Javascript runs until it returns control back to the system and then, and only then, can another piece of Javascript run. That's where the notion of "single threaded" comes from. One piece of Javascript running at a time. It vastly simplifies concurrency issues and, when combined with the non-blocking I/O model, it makes a very efficient system, even when lots of operations are "in flight" (though only one is actually running at a time).

Yes, node.js has some threads inside of libuv that are used for things like implementing file system access. But those are only for native code inside the library and do NOT make your Javascript multi-threaded in any way.

Now, recent versions of node.js do have Worker Threads which allow you to actually run multiple threads of Javascript, but each thread is a very separate environment and you must communicate with other threads via messages without the direct sharing of variables. This is relatively new to nodejs version 10.5 (though it's similar in concept to WebWorkers in the browser. These Worker Threads are not used at all unless you specifically engage them with custom programming designed to take advantage of them and live within their specific rules of operation.

jfriend00
  • 683,504
  • 96
  • 985
  • 979