Multithreading in C++
What is the Thread?
In C++, a thread is a type of working unit used in a particular process. There are some different processes that are executed simultaneously in the multi-programming operating system.
In the same way, with the help of threads, we can execute the same process multiple times. In this case, each process is associated with a unit called a thread. In multithread processes, there are many threads executed simultaneously, which are independent of one another.
Working of <Thread>
We can create a new thread object with the help of std::thread then we can pass that newly created thread to a callable. Here callable is a type of executable code which is executed during the running of a thread. So whenever there is a need for a thread, we just have to create the object and pass a callable as an argument to its constructer. Once a new thread object is created, then the new thread is launched, and the callable code is executed.
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.