I have problem with pthread_join(), hope everyone answer. I am running the program below, and have one row to be printed out. After that, I am trying to delete "pthread_join(th,&val), and no row to be printed out.
I found out all function in program, but i don't understand why.
Can you help me, I am appreciated all answers.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SMALL_STACK 131072
pthread_attr_t thread_attr;
void* fn(void* arg);
int main(int argc, char** argv)
{
pthread_attr_init(&thread_attr);
pthread_attr_setstacksize(&thread_attr, SMALL_STACK);
pthread_t th;
pthread_create(&th, &thread_attr, fn, (void*)14);
void* val;
pthread_join(th, &val);
return 0;
}
void* fn(void* arg)
{
printf("arg = 0x%x\n", (int)arg);
return NULL;
}
Yes that is what pthread_join
is meant to do. It has the calling thread wait until the created thread has done its work. If you don't have it, your main
thread terminates the whole process before your fn
thread had a chance to print.
If for one reason you want to terminate the main
thread and keep all other threads of the process running, you'd have to terminate it with pthread_exit
, not with a return
statement nor with a call to exit
.