Multi Tasking in an application can be achieved by either creating multiple child process (using fork) or multiple threads.
Thread Vs Process:
Process:
- It is an instance of running program or application.
- All process have at least one thread of execution.
- When new process is created then address space is set up in memory for this process.
- Each process is executed in a separate address space, one process cannot access the other process.
- Process is an address space with one or more threads executing within that address space.
- Address space include : stack, heap, data segment and text segment.
- Each process is started with “main()” function in code.
Thread:
- A thread is “sequence of control” within a process.
- A thread is a “particular execution path” of a process.
- A thread has a “initial function” which is where thread execution begin, this section of code is executed parallel with process.
- A thread exists within a process and share the process resource.
- If one thread change the process resource then this modification will be visible to sibling thread.
- All threads will be executed in process address space.
- All threads have own stack and own register.
- All threads will share data segment and heap with the process, who created them.
- All threads will share global variables, file descriptors, signal handlers, current directory state with process that created it.
Advantage of multi-threading over multi-processes:
- Cost creation of thread is less.
- Performance improvement.
- Better utilisation of Hardware resource.
- Switching between threads easily.
Disadvantage of threads:
- Design is not easy for multi-threading.
- Debugging is tough.