All Articles

Asynchronous vs Multithreading vs Multiprocessing

This article was done using my notes from:

Nasser Hussein, (2020), Asynchronous vs Multithreading and Multiprocessing Programming (The Main Difference). Youtube.

Synchronicity

Synchronous operations occur when your make a request, whether it is a network call or to disk. In this process, there is usually one thread doing the work. If you want to read from disk, your thread is basically blocked and waiting for the response to be sent. Meanwhile, the disk controller is making the work. As such, the rest of your code is blocked. It is called synchronous execution.

Multithreading

Think of a process as a container, which executes one thread all the time. You, as the process owner, can decide to run another thread to do some other work. The threads will share the ressources contained in this process.

Shared ressources is a source of difficulties while using threads. Threads will start racing for the common ressources, namely memory locations. You will end up implementing locks on these ressources to avoid race conditions. Building thread-safe applications is a very hard thing to do. Thread safe means implementing mutex (locks) so that your threads cannot access the same ressources at the same time.

Asynchronicity

Node.js is very good example of asynchronous implementation. It is a single thread non-blocking framework. Asynchronicity is the idea that in a process, you only have a single thread. Upon sending a request to disk, the thread uses a callback which will be called when the response from the disk will be ready. Meanwhile, the thread will keep on executing the rest of the code.

Multiprocessing

Instead of spinning up threads sharing the ressources of a process, you can spin several unique processes with their own memory structure, resources, own everything. If you need communication between processes, you can use interprocesses communication. You can use shared ressources, such as a centralized Redis database.