Thread joinable() function in C++
Last Updated :
26 Oct, 2018
Thread::joinable is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output and checks whether the thread object is joinable or not.
A thread object is said to be joinable if it identifies/represent an active thread of execution.
A thread is not joinable if:
- It was default-constructed
- If either of its member join or detach has been called
- It has been moved elsewhere
Syntax:
std::thread::joinable()
Parameters: This function does not accepts any parameters.
Return Value: It is a boolean type function and returns true when the thread object is
joinable. It returns false if the thread object is not joinable.
The following program demonstrate the use of std::thread::joinable()
Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
void threadFunc()
{
std::this_thread::sleep_for(
std::chrono::seconds(1));
}
int main()
{
std:: thread t1;
cout << "t1 joinable when default created? \n" ;
if (t1.joinable())
cout << "YES\n" ;
else
cout << "NO\n" ;
t1 = std:: thread (threadFunc);
cout << "t1 joinable when put to sleep? \n" ;
if (t1.joinable())
cout << "YES\n" ;
else
cout << "NO\n" ;
t1.join();
cout << "t1 joinable after join is called? \n" ;
if (t1.joinable())
cout << "YES\n" ;
else
cout << "NO\n" ;
return 0;
}
|
Output:
t1 joinable when default created?
NO
t1 joinable when put to sleep?
YES
t1 joinable after join is called?
NO
Note: The third output will appear 1 sec later because the thread was put to sleep for 1 minute.
Share your thoughts in the comments
Please Login to comment...