Multithreading in C++ 11 — Part 1: Launching Threads
This article tries to give an idea of most widely used threading constructs in C++. We will use constructs from C++ 11 , and this is the standard where the threading support first came appeared. Prior to C++11 programmer have to rely on pthread_ api to do the multithreading. The new C++11 standard makes a more standardized thread support in all the platform where C++ compliant compiler is available
How to launch a thread?
Well you several options: thread(function,arg1,arg2…) function is on common way to launch a thread async(mode,function,arg1,arg2…) function is another widely used method. The advantage of async() method is that you can get the return value of the function for which the thread is invoked (using futures). thread() api can’t do that. Now there are language nuances on how we can specify the class member function , global function , lambda function and a functor within the thread() api. Please check the bitbucket code below for details.
How many thread should i launch in a machine?
Well if your threads are compute intensive than it does not make sense to lanuch more than what your CPU can support. You can get this value programitacally using thead::hardware_concurrency(). If you are planning to launch a thread for tasks which involve IO operations (and most of these are waiting for a long time) you can launch more than what hardware_concurrency() can support. This is what the many servers does, for each connection they open a thread but many of the connections are ideal most of the time. Here also you have to be careful about the limits of “number of threads running concurrently” and many attacker exploit this for DOS attacks.
What about the packaged_task()?
A packaged_task is a task( function with or without its argument values) which can be exectuted later by a thread. packaged_task is useful as you can push them in a queue for processing and worker thread can pick them up and execute them.
Here is my notes which captures all we talked about above