Async vs Multithreading
I have been in a misconception for quite a while on this. I just assumed that whenever we say let's make it async we should just spin up another thread for this task and let the main thread continue without waiting. And until now I never thought about this actually. But then I was studying the internals of OS and how multithreading actually happens (virtual and physical) and it got me thinking if all that assumption was even valid.
I started looking to deep dive into this and then I got to know about nodejs, and javascript.
Node js specifically mentions single-threaded non-blocking async functionality. This drew my attention more towards that as I was in a little shock to be honest. It got me thinking about how CPU schedules with time slices on a single core.
Mostly we write simple code where each line executes 1 by one and that's a blocking code. Like if we make a for loop and call that, the thread actually waits for that to complete to proceed forward. This we call blocking code. Now if we see in nodejs we can make calls using async and provide a callback function to that which would be notified when that code completes. This could be anything like sending an email, reading from some file or any IO-bound operation. So it's all going in that same thread (with time slicing) and to us, it is non blocking lines of code. So we are not waiting to finish tasks for which we don't want to.
Let's take an example: Suppose you are taking a break in the office in the cafeteria. Now you have to drink coffee/tea as well as have other things like reading books/making calls. So in node js way you can put the machine to make coffee while making a call and when coffee is brewed you take that along with you. So you didn't wait here for coffee and continued other work and consumed when that background coffee was done.
Now we can also see the above in multi threaded way. Suppose there's a waiter also and you asked him to make a coffee while you continue doing your own stuff. You received your coffee from a waiter and consumed it. Here you employed an extra person for another task (coffee) which we can relate to as another thread in our program to let's say send an email, and save to a file.
So we can actually say Multithreading is one way to do async programming. Async can even be on a single thread.
This example would have cleared the point I wanted to make. Just implement this with simple code and see for yourself.
Let me know if anything I might have missed.