Multi-threading
- Multithreading is the term used to run multiple threads inside a single process in order to execute multiple tasks at the same time.
- Multithreading can be done by using CPU threads via the operating system or using programming language ability to run multiple threads.
- Currently, most of the applications use multithreading in order to provide a better user experience.
Process
- The process is the main unit used to execute the given task in the operating system.
- The process has some system resources like memory, CPU, disk, etc. in order to complete the given task. A single process can execute only a single task at a given time.
Thread
- Thread is a subprocess or tiny process which runs inside a process.
- Thread uses the process resources and provides the ability to run multiple tasks at the same time by using a given Central Processing Unit (CPU) cores or thread functions.
Types
There are two types
- Pre-emptive: In pre-emptive multithreading, the operating system decides the context switching which means the pausing of the given thread and running other threads. For example, a low-priority thread can be started by pausing a high-priority thread.
- Cooperative: In cooperative multithreading, the context switching is controlled by the threads. The active thread will pause itself and switch to the next thread voluntarily. But this type of switching can create some deadlock because the threads can be managed and check the OS resources.
Uses
- Games require a lot of processing power where multiple threads can be used to accomplish different tasks and provide this processing power.
- Today IT creates a lot of data that is very hard to process. Single processes can not consume big data in a given time frame. We can use multithreading in order to divide the big data into multiple parts to processes with multiple threads
Advantages
- Efficiency: Creating a thread is very efficient where the same resources of the given process are used.
- Resource Sharing: As stated in the previous step the thread will use the given process resources which will make the resource usage lesser.
- Responsiveness: By running multiple tasks at the same time the responsiveness can be improved.
- Scalability: A single big task can be divided into multiple little tasks and these tasks can be run in multiple threads which will scale the big task.