Reputation: 41
Is it possible to re-use a condition variable in a loop? I tried to create a thread pool and whenever a thread's turn comes main thread signals using the condition variable. In the beginning, the thread will wait for the signal and after this, it'll do its job and keeps looping until the loop ends. I tried this below
// one of the threads in the thread pool
while(a condition){
pthread_cond_wait(&cond, &lock);
pthread_mutex_lock(&lock);
// job
pthread_mutex_unlock(&lock);
}
// in main thread, whenever a condition happens
// for a specific thread, main thread signals using condition variable
pthread_cond_signal(&cond);
What's wrong with this code?
Upvotes: 1
Views: 619
Reputation: 41
Thank you all for answering this question. I gathered both your answers and the sources I found online and found a solution for my own question. The order should be like this:
// thread1
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
// job
pthread_mutex_unlock(&lock);
// main thread
pthread_mutex_lock(&lock);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
Upvotes: 1