Example of std::thread::join()
The below example demonstrates how to use the std::thread::join() function to join the threads.
// C++ program to illustrate
// std::thread::join() function in C++
#include <iostream>
#include <thread>
using namespace std;
void thread_function()
{
for (int i = 0; i < 2; i++)
cout << "Thread function Executing" << endl;
}
int main()
{
thread threadObj(thread_function);
for (int i = 0; i < 10; i++)
cout << "Display From Main Thread" << endl;
threadObj.join();
cout << "Exit of Main function" << endl;
return 0;
}
Output
Display From Main Thread
Display From Main Thread
Thread function Executing
Thread function Executing
Exit of Main function
Important Points:
- The
std::thread::join()
function blocks the current thread until the thread identified by*this
finishes its execution. If the thread has already finished execution, thenjoin()
returns immediately. - The
join()
function is used to ensure that a thread has completed its execution before the program exits. Ifjoin()
is not called before the main function finishes, and the thread is still executing, then the program will terminate abruptly. - A thread can be joined only once, and once it is joined, the thread becomes unjoinable. If you attempt to join a thread more than once, the program will terminate.
- If you want to make the thread unjoinable without blocking the current thread, you can use the
detach()
function instead ofjoin()
. However, you must be careful when usingdetach()
, because if the main thread finishes execution before the detached thread, the program will terminate, and any resources used by the detached thread will not be cleaned up.
std::thread::join() in C++
The std::thread::join() is a standard library function in C++ that is used to block the current thread until the thread identified by *this finishes its execution. It means that it will hold the current thread at the point of its call until the thread associated with that join() function finishes its execution.
It is defined in the <thread> header file as a member function of the std::thread class.
Syntax of std::thread::join()
void join();
Parameters:
This method does not accept any parameters.
Return Value:
This function does not return a value.
Contact Us