Do you know what is the context switch?
Hey, I am Axel from Grape Programmer. Today, I want to introduce to you some basis about System Programming in multithreaded environment.
The purpose of Context Switch
The context switch is a procedure done by a computer CPU. It allows switching from one single task/process to another one. This procedure helps to avoid conflicts between those tasks.
Otherwise, The word "context" concerns all the data stores and used to follow correctly a process. It means that values in registry, like process instructions, are stored or redeployed in registry.
When the context switch is called? It can be called by:
- Multithreading - Following the conditions (Like mutexes, conditions...), the context switch can be called to switch from one thread to another one.
- Interruption - Specifically used to interrupt CPU usage in order to access data in hard drive.
- Switch between user and kernel mode - This is more called a "mode switch". Here, to run a specific kernel routine (like system call, signals, networking...) it could require a process state saving.
What is the cost of a Context Switch?
A context switch cost can be expensive in terms of time execution.
Indeed, the fact of saving process state or restoring a process state is not free! Of course, the cost of switching depends on your hardware architecture.
It is not rare to see a multithreaded application which is slower than a single-threaded one. In general, this kind of issue is due to design purpose (like tentative to migrate a single-thread application to a multithreaded one... Which is rarely a good idea). Due to multiple thread synchronization, the number of process switches are excessive, slowing down the execution time.
Quick word, the case of cout/printf
In my very first post, I talked about the usage of cout/printf:
I have one remark to complete my first post:
Mostly, A simple"printf"/"cout" call can trigger a context switch. Indeed, if the I / O stream is already locked by another thread, we should wait for the availability of I / O stream. Then, a context saving. So, a future switching.
For your multithreaded application, my recommendation is to load a logger library like glog or spdlog!