I have the test code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t th_worker, th_worker2;
void * worker2(void *data) {
for(int i = 0; i< 1000000; i++){
printf("thread for worker2----%d\n", i);
usleep(500);
}
}
void * worker(void *data){
pthread_create(&th_worker2, NULL, worker2, data);
for(int i = 0; i< 100; i++){
printf("thread for worker-----%d\n", i);
usleep(500);
}
}
void join(pthread_t _th){
pthread_join(_th, NULL);
}
In main() function, If I call join(the_worker2):
int main() {
char* str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void*) str);
/* problem in here */
join(th_worker2);
return 1;
}
--> Segment Fault error
Else, i call:
join(the_worker);
join(th_worker2);
---> OK
Why have segment fault error in above case? Thanks for help !!!
If you posted all your code, you have a race condition.
main
is synchronized with the start ofworker
but notworker2
.That is,
main
is trying to jointh_worker2
beforeworker
has had a chance to invokepthread_create
and set upth_worker2
with a valid [non-null] value.So,
th_worker2
will be invalid until the secondpthread_create
completes, but that's already too late formain
. It has already fetchedth_worker2
, which has a NULL value andmain
will segfault.When you add the join for
th_worker
, it works because it guarantees synchronization and no race condition.To achieve this guarantee without the join, have main do:
An even better way to do this is to add an extra variable. With this, the first loop is not needed [but I've left it in]: