Home > database >  efficiency of javascript's concurrency model
efficiency of javascript's concurrency model

Time:06-09

As we known, JS use event loop to simulate multi-thread on single thread. I'm confused about its efficiency.

Assume we want to read a file and there's a way to use the linux read system function. According to my knownledge, while read function is running, CPU will send the job to DMA so that CPU can do other things.

In other real multi-threading languages like C , we create a new thread to read the file. While DMA is processing the file, CPU can really switch from that file reading thread to do some other jobs.

But in JS, there's only one thread that really working. Even now you put this reading file job away, but in the future you must do that job on this thread. Whenever you want to call read function, you must already in THE thread's stack, even though CPU can leave the job to DMA, THE thread is still blocking there and can't jump to other thread (cause there's only one thread, right?)

So I think JS's event loop model is not really concurrency, right? Even though it can put job away temporarily, it still need the same amount of time to deal with the job. The total executing time is not reduced. I'm confused and help me please.

CodePudding user response:

Even if JavaScript were single-threaded (which it no longer is thanks to Web Workers), you could ask the operating system to perform many I/O operations concurrently:

Rather than using blocking I/O, where we ask the OS to put the thread to sleep until the data is here, we can use non-blocking I/O, where we ask the OS to fetch data, and notify us when it's here, allowing us to do other things in the mean time.

For instance, in the node.js file system API, every function exists in several flavors:

  • The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails.
  • The callback APIs perform all operations asynchronously, without blocking the event loop, then invoke a callback function upon completion or error, (the callback APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread).
  • The Promises APIs, which work like the callback APIs, but are easier to use.

so we can choose whether we wish to sleep until the data is here, or do other things in that time.

It's worth noting that actual hardware is non-blocking. For instance, Direct Memory Access allows a disk to put data in memory without involving a CPU, and interrupt the CPU once the transfer is complete.

CodePudding user response:

You can run real multi-threading in javascript using web-workers. You cannot simulate multi-threading in a single-threaded environment. Async and multi threading are not the same thing. You can run async in javascript but not multi-threading (without the WebWorkers).

  • Related