Do you know how to avoid thread creation trap in C++? This quick post is a parallel with one of my previous ones, the context switch (Don't hesitate to check it!)
What happens when a thread is created in C++?
A thread creation in C++ is not free. To avoid details and give a quick description, we can resume a thread creation to this:
- Initialization of the thread - In the stack, instructions (and variables) are created. Memory consumed.
- Starting of the thread - Potentially launch of the context switch. Thanks to std::thread (C++11), the thread execution is launched at constructor time.
Finally, all those instructions consume CPU time. In fact, Multiple threads creation in your application can cost heavy, specially for the next reasons...
Thread creation trap in C++ - Synchronization
Few years ago, during my job, my team received a proposition to migrate a piece of single threaded code to a multithreaded one. Great, the management and product owners was happy to hear that, let's develop now!
It was not really a good idea...
Indeed, we jumped to a new kind of behavior without any design modification. The consequences was terrible:
- Deadlocks.
- Race condition - Variables was not correctly protected.
- Effects on IUI.
Despite that the application was more reactive, bugs was harder to detect (and can effect other component due to instability). Finally, a design modification had been necessary.
Thread creation trap in C++ - Context switch
A multithreaded application is not necessary quicker than a single threaded one. Actually, I already described this in one of my previous post:
July 18, 2020
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 SwitchThe context switch is a procedure done by a computer CPU. It allows switching from one single task/process to another one. This procedure
To summarize, each thread can trigger a mechanism named "Context Switch". Each switching of context is a CPU cost more or less important.
Indeed, migrating a single threaded application to a multithreaded one will imply the "Context Switch". This context switch can damage the performances of your application.
To conclude, each thread creation should be evaluated properly. It requires:
- Design review, thread synchronization - Semaphore, Mutex, Signals...
- Variable protection - Mutex
- Performance analysis - Context Switch impact.