1

I am very much confused with the usage of join() and detach() threads. Could anyone explain the logics and purpose of using both. Is it possible to use both functions in a same program?

When i run the below mentioned program the cout statment in check function is executed 5 times. whereas if i replace join() with detach() and run the same program, the cout statement in check function is executed only 4 times. Do anyone know the reason for this ?

#include <iostream>   
#include <string> 
#include <thread>
int *check(){ std::cout<<"entering check func"<<std::endl; return 0; }
int main() {    
    for(int i=0; i < 5; i++){    
    std::thread t(&check);   
    t.join();  
   } return 0;
  }
Mukhila Asokan
  • 641
  • 3
  • 11
  • 29
  • Also see http://stackoverflow.com/questions/3756882/detached-vs-joinable-posix-threads – Arunmu Jul 01 '16 at 05:56
  • Also refer to this [Link](http://stackoverflow.com/questions/22803600/when-should-i-use-stdthreaddetach) – Vineet Kumar Jul 01 '16 at 06:01
  • @Arunmu Thanks for the links. I have already referred to the links, but still it is unclear. Can we use join and detach functions in the same program.If so what would be the result? – Mukhila Asokan Jul 01 '16 at 06:07
  • @sathish Can you quote something specific which you could not understand ? Maybe that will help others to know what exactly you are having trouble understanding. – Arunmu Jul 01 '16 at 06:46
  • @Arunmu Please refer to the code in the question – Mukhila Asokan Jul 01 '16 at 07:18
  • 1
    @sathish The program exits before 5th thread gets a chance to execute the `cout` statement. There is no definite behaviour here, it could even print 3 times or 0 times. With `join` as explained in the duped question, it will wait for each thread to finish its execution and only then `main` will finish. – Arunmu Jul 01 '16 at 08:00

0 Answers0