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
Detaching the thread does not guarantee it will have time to finish running. You have a race condition in the program. Once
mainreturns, the entire program exits.Try adding a sleep to the end of the main program and see the difference.