Reputation: 65
Forgive me I'm just beginning the concept of multi-threading, I was just wondering why my threads might be exiting before they're joined. Essentially, I am maintaining a global list of process id's, I create them iteratively by calling
if(pthread_create(&thread_id[i], NULL, function_to_execute, NULL)) {
fprintf(stderr, "error thread not created\n");
}
Now the problem is, all my threads are exiting before they get to my pthread join
pthread_join(thread_id[i], NULL);
which is deeply nested in a function call, which is called directly after the threads are created. I'm not sure if I'm suppose to do some locking or something, or add an additional command to make sure the threads wait until the join statement before exiting.
Upvotes: 2
Views: 4802
Reputation: 852
I'm not entirely sure why it would be a problem if threads are finishing before their exit status is claimed by pthread_join()
?
This is perfectly normal.
pthread_create()
starts new thread of execution at the specified function. The function runs immediately and may even preempt the starter thread. A thread has its own local variables (stack) and thread-local variables. All other shared memory accesses must be coordinated or data-racing will happen. Usually shared data is protected by mutexes. Thread will continue to run (usually parallel with other threads) until it is either blocked by some synchronization operation or thread exits the its start function.
The thread can wait with pthread_join()
for other threads to finish execution successfully. Like usr noted pthread_join() won't wait if thread is already finished.
Upvotes: 0
Reputation: 121377
From POSIX documentation:
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread shall not be detached.
So, no. You don't need to take any additional measures as long as you satisfy the above requirements.
Upvotes: 2