Multithreading in C++
Vanshika Munshi
Senior Consultant-Client Relationship & Delivery Management at HuQuo
Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.
Multithreading support was introduced in C++11. Prior to C++11, we had to use?POSIX threads or <pthreads> library. While this library did the job the lack of any standard language-provided feature set caused serious portability issues. C++ 11 did away with all that and gave us?std::thread. The thread classes and related functions are defined in the?<thread>?header file.
Launching Thread Using Function Pointer
A function pointer can be a callable object to pass to the std::thread constructor for initializing a thread. The following code snippet demonstrates how it is done.
Launching Thread Using Lambda Expression
std::thread object can also be launched using a lambda expression as a callable.?
Launching Thread Using Function Objects
Function Objects or Functions can also be used for launching a thread in C++.
Waiting for threads to finish
Once a thread has started we may need to wait for the thread to finish before we can take some action. For instance, if we allocate the task of initializing the GUI of an application to a thread, we need to wait for the thread to finish to ensure that the GUI has loaded properly.
To wait for a thread, use the?std::thread::join()?function. This function makes the current thread wait until the thread identified by?*this?has finished.
A Complete C++ Program For Multithreading?
A C++ program is given below. It launches three threads from the main function. Each thread is called using one of the callable objects specified above