Let me show you the function first:
for (i=0; i<3;i=i+2){
pthread_create(&thread1, NULL, &randtrack, (void *)&rnum_array[i]);
pthread_create(&thread2, NULL, &randtrack, (void *)&rnum_array[i+1]);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
}
print final result here;
My understanding is after two threads are created, the parent thread will blocked at join(thread1), what is the thread 2 actually come back earlier than thread1? How can make longer thread always stay behind?
Thanks
If
thread2finishes andthread1hasn’t, you’ll continue waiting untilthread1finishes. Then you’ll wait untilthread2finishes, which will complete more or less instantaneously. The order in which you wait for the threads won’t matter (unless the threads try to interact with each other directly, such as by callingpthread_killorpthread_joinon each other).Update: Your design is completely wrong for what you’re actually trying to do. You want to do this:
Create a structure to track the work that needs to be done. It should be protected by a mutex, track how many threads are currently working, and what the next work unit that needs to be assigned is.
When you create the threads, have them rung a function that acquires the mutex, grabes the next unit of work, increments the number of threads running, and then does the work.
When a thread completes a work unit, it should acquire the mutex, decrement the number of threads running, and see if there’s more work to do. When there’s no work to do, the thread should terminate.
You can now wait for all threads to terminate, which will only happen when all the work is done. This eliminates the loop over the work units.
And please learn a very important general rule — threads are just the things that get work done. What you want your code to focus on is doing the work, not how it will be done. Try to wait for work to be done, not for threads to be done.