I see that many people fail to understand the difference between asynchronous programming and multi-threading. Let’s try to look into it today. We will see the below topics at a high-level today.
- Process & Threads
- Asynchronous Programming
Process & Threads
By Definition, a thread is the smallest sequence of programmed instruction that can be managed by the operating system. A thread is the smallest unit of work that your computer can perform. Threads are part of the CPU and are very crucial in the functioning of a computer. It is always advisable to be careful whenever you are working with threads as they form the basic resource for our CPU and should be treated in a more cautious way than memory. In fact, many programming languages like C#(Tasks), Go(Goroutines), and Kotlin(Coroutines) provide an abstraction around the thread to make it simpler to work with threads. We will try to understand threads a bit deeper after learning the definition of a Process.
A Process is an instance of a computer program. It contains program code and its activity. A process may be made up of single or multiple threads. When you run any program, that becomes a process. A process will use at least a single thread for its execution. Threads are the bridge connecting your program (which is your process) to your CPU (or computer).
A single-threaded process is a process that can perform only one task at a time. Let’s consider a printer. When you give instruction for a printer to print, even if you send multiple pages for the printer to print it will only print one page at a time. This is because the process of printing a page is a single-threaded process.
A multi-threaded process is a process that uses more than one thread. Most of the computational processes are multi-threaded. For example, when you are typing in a workpad, there is a thread that is listening to the user input and then displaying it on the screen, and there is a thread checking for any spelling mistakes.
As mentioned in the example above, a printer queues all the requests and prints one page at a time. This kind of process is known as a synchronous process. A program like a word, which performs some operations in the background without blocking the main thread (GUI thread in this case) is called an asynchronous program. Imagine if we had to wait for every second after we type a word in wordpad for the spellcheck to happen. Won't it be frustrating? That’s is why it is always better to have our program as asynchronous.
This is a question I get lots of time, as people often confuse multi-threaded processes with asynchronous programming.
The answer to that is that you can have your program run in a single thread without blocking it in any way.
Hope I have managed to shed some light on Threads and Asynchronous programming.
Top comments (0)