My program is seemingly having a deadlock problem.
Basically I have a class that looks like this:
class Foo {
public:
Foo();
void bar();
private:
void monitor();
bool condition_;
pthread_t monitor_;
pthread_mutex_t mutex_;
pthread_cond_t cv_;
};
In Foo‘s constructor, I invoke monitor() in a separate thread (namely monitor_). This monitor() function does the following:
pthread_mutex_lock(&mutex_);
while (true) {
while (!condition_) {
pthread_cond_wait(&cv_, &mutex_);
}
// do something
// and then setting condition_ to false
condition_ = false;
}
pthread_mutex_unlock(&mutex_);
The bar() function is the only public interface (excluding ctor and dtor) of Foo. It also needs to acquire the mutex in its execution. My symptom is that bar() can never acquire mutex_. It looks like pthread_cond_wait() does not release the mutex as it is supposed to do. And if I disable the monitor thread (thus no racing condition), then bar() can run to its completion without any problem.
Of course, the above code is a stripped-down version of my real code. Actually I think there is no logic error in this code and I’m using pthread correctly. I’m suspecting if there are any other causes for this deadlock situation. Can anyone give a clue on this? Thanks!
I would look at your constructor and the bar() function, and possibly if you’ve accidentally made a copy of the object in question. I’ve copied the classes you provided, and my assumptions on how the rest of it operates below. The program below wakes up every second, and signals the thread.