0
donuts
5y

If I have several nodejs apps and JS being single threaded, how do I know that when I start all of them, they aren't running on a single cpu?

I'm. Not sure if I'm understanding it correctly but say I start 1 app, that means all the app's work will be done on whichever cpu it was started on? Or can it spawn additional threads and on other cpus to do (nonjs) work?

Comments
  • 0
    Every of your apps should run as its own process.
    Every process allocates, at least, one os-thread.
    Your kernel schedules all existing os-threads onto the available cpu-threads.
    Its possible, that an os-threads locks itself to a specific cpu-thread, but that's usually done explicitly, not implicit.
  • 0
    @metamourge so each node process will probably be assigned by os to a different cpu. But node/JS single threaded refers to the os-thread you mentioned? But if the code calls fs.readAsync() that will actually be executed on a different thread and possibly on a different cpu?
  • 1
    @billgates
    Yeah, all JS-code will be run inside a single os-thread.
    I don't know, how the eventloop works on the inside.
  • 0
    @billgates i’m not an expert but someone can correct me

    You execute a js script. A process is started with a single thread. That thread executes your js code, let’s call it userland code.
    Let’s say something async is done (and by async I mean a libuv backed async task, like reading a file in node).
    Another thread starts that executes the libuv code for that.

    whether the threads of a process execute in some core or another core in the cpu depends totally on how the scheduling of the kernel works and it’s transparent and irrelevant to node or js thread usage.
  • 0
    @jesustricks but all applications start with a single thread? And can start other threads for background work. So how is JS a single threaded language if it can offload work into multiple threads?
  • 0
    Actually I think i found it, the js app is single threaded but JS is part of Node or the engine which can multithread.

    https://dev.to/steelvoltage/...

    So I guess it's like a webapp n server communicating via Ajax or JSONP
  • 1
    @billgates js itself is single threaded in the sense that strictly js code, userland code, is single threaded.

    In js, you can’t directly manipulate threads: you can’t create them, close them, share resources between them.

    Nodejs and web workers create separate threads and execute things with them, but the usage of threads is hidden away from you.

    Good question btw
  • 2
    @jesustricks to summarize: everything in node runs in parallel (libuv Backend), except your userland Code.

    Node js got some additions with worker threads to do real parallel working and offloading tasks
  • 1
    @Minion thank you, I forgot about worker threads. There’s also web workers in the web.
Add Comment