joinable() function help us to know whether thread object has a ACTIVE thread or not. Thread remain ACTIVE although it has finished its execution.
Term ACTIVE can be more appropriate to explain as
- Thread Object is/was assigned with a task by calling constructor.
- Operations join() or detach() are not called on that thread object.
Thread created with default constructor is in non ACTIVE.
joinable() returns true if thread is active else false.
Let’s try to understand with the following examples that is easy to understand.
For better understanding you can copy and paste it in online compiler.
#include<iostream> #include<thread> //Thread Header //to be performed by our thread void displayActivity() { cout<<"www.techsujhav.com "<<endl; } int main() { cout<<"Going to start thread"<<endl; //hence joinable output::ACTIVE state is false (0) std::thread t_obj; cout<<"Thread before task assigned, (ACTIVE) joinable= "<<t_obj.joinable()<<endl; //hence joinable output::ACTIVE state is true (1)
t_obj=std::thread(displayActivity); cout<<"Thread after task assigned, (ACTIVE) joinable= "<<t_obj.joinable()<<endl; //hence joinable output::ACTIVE state is false (0) t_obj.join(); cout<<"Thread after join() operation, (ACTIVE) joinable= "<<t_obj.joinable()<<endl; //hence joinable output::ACTIVE state is true (1) t_obj=std::thread(displayActivity); cout<<"Thread after new/re-assigned task, (ACTIVE) joinable= "<<t_obj.joinable()<<endl; //hence joinable output::ACTIVE state is false (0)
t_obj.detach(); cout<<"Thread after detach() operation, (ACTIVE) joinable= "<<t_obj.joinable()<<endl; cout<<"Main Exit"<<endl; return 0; } |
Compile:$ g++ joinable.cpp -o joinable
-lpthread
|
Output:$ ./joinable
Going to start thread Thread before task assigned, (ACTIVE) joinable= 0 Thread after task assigned, (ACTIVE) joinable= 1 www.techsujhav.com Thread after join() operation, (ACTIVE) joinable= 0 Thread after new/re-assigned task, (ACTIVE) joinable= 1 Thread after detach() operation, (ACTIVE) joinable= 0 Main Exit |
PREV:: std::thread (First Program)
Your Comments /Suggestions & Questions are always welcome.
We would like to help you with best of our knowledge.
So feel free to put Questions.
No comments:
Post a Comment