I'm writing a Unix application in C which uses multiple threads of control. I'm having a problem with the main function terminating before the thread it has spawned have a change to finish their work. How do I prevent this from happening. I suspect I need to use the pthread_join primitive, but I'm not sure how. Thanks!
Yes one of doing this is to use pthread_join
function: that's assuming your thread is in "joinable" state.
pthread_create
: after this function returns control, your thread will be executing your thread function.after
pthread_create
, use the tid from pthread_create topthread__join
.
If your thread is detached, you must use some other technique e.g. shared variable, waiting on signal(s), shared queue etc.
Great reference material available here.
You may want to look at this page: http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/apis/users_25.htm
rc = pthread_create(&thread, NULL, threadfunc, NULL);
checkResults("pthread_create()\n", rc);
printf("Wait for the thread to exit\n");
rc = pthread_join(thread, &status);
Yes, you could use pthread_join() (see other anwers for how to do that). But let me explain the pthread model and show you another option.
In Unix, a process exits when the primary thread returns from main, when any thread calls exit() or when the last thread calls pthread_exit(). Based on the last option, you can simply have your main thread call pthread_exit() and the process will stay alive as long as at least one more thread is running.
There are a number of different ways you can do this, but the simplest is to call pthread_exit()
before returning from main().
Note that this technique works even if the thread you want to wait for is not joinable.