简体   繁体   中英

What is the difference between multi-threading and asynchronous in NodeJS

NodeJs add multi-threading feature in latest update.

I would like to understand with simple examples what is the difference between multi threading and asynchronous ? In which cases we should use multi-threading than asynchronous ?

First thing to understand is that different parts of the computer works at different speeds. Disk, Network etc...

So if you notice asynchronous code seems to only deal with network, or files for a good amount of stuff, let's call that io.

Ok, cool.

Now let's think that through, your code is running and you need to read a file. In cpu time. This is "1000s of years" so the cpu says. Hey when the data is available you let me know. Imma go do some other sh*t.

Then the disk comes back and is like hey I got that data you wanted. Cpu like? Data oh that thing I was "await"ing on.

You can see how this can be more efficient.

Now what if you aren't getting data. What if your cpu needs to do more than one thing.

Follow this, in the morning you might make a sandwich while pouring some juice. It's hard to do both right?

But you can easily pour juice while awaiting your eggs to cook.

Threads... Threads are to get more hands. I need to do more tasks such as shrink the size of an image, I can't wait for the image to shrink. I need to actively shrink the image, but I need to respond to other people, I need to shrink multiple images, I can't do it only one at a time.

So now you get the concept let me actually explain the damn thing.

Asynchronous code creates a dumb thread that just waits for io, like disk or network. It's still a thread but the code handles it for you pretty nicely. It solves a bunch of complex work for you. You just write await and async.

Threads normally you have to manage alot more of it. Think about it this way.

Read from disk, read from network.. they are fairly obvious things and you could make sure you create an API around that. But cpu work, there are infinite things a cpu can be made to do. Threads normally involves more manual work.

Lastly a thread can only do one thing. Pour your orange juice and butter your sandwich with one hand. Hard right? Might need threads, extra hand.

Now cook your eggs and cut some watermelon with one hand. You can see how you can await for some stuff to finish and go do other things.

Go.. you a man now!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM