std::thread::joinable() Function
The thread has to be joinable for the join() function to work. We can check whether the thread is joinable using the joinable() member function of std::thread class.
Example of std::thread::joinable()
// C++ program to illustrate
// std::thread::joinable() function in C++
#include <iostream>
#include <thread>
using namespace std;
// thread callable
void thread_function()
{
for (int i = 0; i < 2; i++)
cout << "Thread function Executing" << endl;
}
int main()
{
// creating object of std::thread class
thread threadObj(thread_function);
for (int i = 0; i < 10; i++)
cout << "Display From Main Thread" << endl;
// detaching thread
threadObj.detach();
// checking if the thread is joinable.
if (threadObj.joinable()) {
threadObj.join();
cout << "Thread is Joined" << endl;
}
else {
cout << "Thread is not joinable." << endl;
}
cout << "Exit of Main function" << endl;
return 0;
}
Output
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Display From Main Thread
Thread is not joinable.
Exit of Main function
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