Home > Web Front-end > JS Tutorial > Javascript is NOT single threaded!!

Javascript is NOT single threaded!!

王林
Release: 2024-07-23 11:57:20
Original
727 people have browsed it

NO! you have not learned wrong that JavaScript is a single threaded language. It is a single-threaded language it has access to a single main thread to execute the code. So when we talk about synchronous programming, we are talking about this lone thread doing all the heavy lifting and executing our code.
Image description

But in reality V8 engine and Node.js use a c library called libuv to get access to six extra threads. Two of these are used for doing garbage collection and the rest are used for doing background tasks like asynchronous programming.

Yes. When we say that code is asynchronous or non-blocking what really happens is the async code is passed to these extra threads with the callback and the main thread keeps on doing its work without blocking the rest of the code.

Javascript is NOT single threaded!!
When the async code is finished, the callback function is pushed into the event queue with either error or the required data. Then the event loop pushes it into the call stack and boom we get our result, to understand this with some code. Let's look at the readfile method of fs module.

fs.readFile("demo.text","utf8",(err,data)=>{
    if(error){       
        return error
    }
    console.log("output",data);
})
Copy after login

In the code above the readfile method is passed to the background threads. The reading to happens in the background, and when that gets finished the callback is pushed into the event queue with either error or data.

Javascript is NOT single threaded!!

Once in callstack the callback is executed and we are left with either error or the data as output.
Thanks for reading I hope I was able to explain about the single threaded means in Javascript.

The above is the detailed content of Javascript is NOT single threaded!!. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template