Thread Detach In Linux System

105 Views Asked by At

what I know is that detach( ) makes the main function not to wait until all threads have finished.

#include <unistd.h>
#include <iostream>
#include <pthread.h>

using namespace std;

void *threadFunction(void *arg){
  cout<<"hello world = "<< *((int*)arg) <<endl;
  return 0;
}

int main() {
  int a = 10;
  pthread_t tid;
  pthread_create(&tid,NULL,threadFunction,(void*)&a);
  pthread_detach(tid);

  cout<<"hello world"<<endl;
   
  return 0;
}

this is the code example, but why the threadFunction isn't being execute, because previously when I ran the code the threadFunction was called but after I ran the code again the threadFunction was not called. Why did it happen ?.

Also sometime i got unexpected value from the thread function,before i got 10 after i got random value

2

There are 2 best solutions below

2
ash On

Detaching the thread does not guarantee it will have time to finish running. You have a race condition in the program. Once main returns, the entire program exits.

Try adding a sleep to the end of the main program and see the difference.

0
John Bollinger On

what I know is that detach( ) makes the main function not to wait until all threads have finished.

No. main() does not wait for threads to finish in any case, unless you explicitly code that. The entire program terminates when main() terminates*, except if it terminates by calling pthread_exit().

The point of detaching a thread is to get the system to clean up after it automatically, instead of waiting until the thread is joined. But you can't have it both ways. A detached thread cannot be joined, which makes it difficult to await that thread's completion.

why the threadFunction isn't being execute?

If you do not see the output from threadFunction() then that's because the program terminates (as a result of main() returning) before that happens. The easiest way to avoid that would be

  1. Do not detach the thread, and
  2. Do join the thread before main() terminates.

Also sometime i got unexpected value from the thread function,before i got 10 after i got random value

The thread function's argument points to a local variable of main(). The lifetime of that variable ends when main() returns, after which point attempting to dereference it produces undefined behavior. The program overall will be in the midst of shutting down at that point, but shutdown is not immediate, so it may sometimes happen that the thread function exercises that UB. Joining the thread would resolve this issue, too.


*Only the initial execution of main() has this property. That makes no difference in C++, which disallows reentry into main(), but it makes a difference in C.