We can sing while having a bath. We can listen to song while jogging. We are multitasking!. Can a computer to do that? How can a computer do that? As a developer how do we do that?
Process vs ThreadLet's take word processor as an example. In a word processor there are spell checker, auto correct, etc. Which means within Word application there are sub tasks are running behind the scene. And those tasks share the same address space as the process.
We name those sub tasks as Threads and main task as a Process.
Back in old days, a computer had only one CPU. On the other hand computer could handle only one task at a time. It switch between tasks very quickly so that we can't see the difference. (Time Slice)
Modern computers come with multiple processors allowing multiple tasks to run at the same time.
When dealing with multiple threads we have to think;
- Two threads update a variable simultaneously.
- One threads depends on another thread.
- Two threads are waiting for each other.
- Thread order (who has the highest priority).
- Will all the threads get chance to execute?.
- and more...
Benefits of multi-threading
- Better resource utilization.
- Better performance.
- More responsive
Costs of multi-threading
- Complex design.
- CPU overhead to switch between threads.
Issues with multi-threadingIn a multi-threaded application will mainly face two kind of problems.
- Visibility issue - One thread change the data while the other thread reading it unaware of the change.
- Access issue - Change same shared data.
- liveness failure - stop reacting (deadlock)
- safety failure - incorrect data produces (race conditions)
- performance - due to switch between threads