I have to write a C application that posts info on web using CURL. The application must run up to N (let’s say 10) requests in parallel at most. How can I wait for ANY thread to finish, rather than specific thread using pthread_join().
I read about pthread_cond_wait, but most examples are how the control thread (main) wakes up a worker thread. I need just the opposite – worker threads must be able to signal/wakeup parent thread before exiting.
Update: Actually I need a way to make manager thread sleep and when a worker thread finishes it’s job it should wake the manager thread to give it another job. It doesn’t matter if the thread will end and new thread will be created for the job or thread pool will be used. Threre still needs to be a way to signal the manager that a job is finished.
I hope that I DON’T get this suggestion:
while(asleep){
for(i = 0; i< threadCount; i++){
pthread_mutex_lock(mutex);
if(threads[i] == IDLE_STATE)
startNewJob();
pthread_mutex_unlock(mutex);
usleep(100*1000);
}
}
Condition variable are what you’re after. They can be used just as easily to signal the manager thread from the worker thread as vice-versa.
Your strawman example at the end is actually very similar to what you could do using a condition variable:
When a thread is done, it would simply do: