Reputation: 401
I am trying to use pthread_cond_wait in the way I think it should be used. I use it in a method, that is waiting for something to change, and when it does it will call another method to get the data. it looks like below:
void waitForSomething(const std::string& _str) {
//lock my mutex here
while (!ifStringInSomeCollection(_str)) {
std::cout << "waiting.." << std::endl;
pthread_cond_wait(&_condMutex, &_myMutex);
}
//unlock my mutex here
//this method also acquires my mutex lock
std::cout << getData(_str) << std::endl;
}
Now in my other method that will break the condition and broadcast/signal the waiting condition, I first unlock the mutex before broadcasting/signalling - so that should not be an issue.
But even without that, what currently happens is, it constantly checks for condition in the while loop instead of pthread_cond_wait - actually waiting. I've been stuck with this for a while, any ideas would be much appreciated. Thanks!
==================
Following discussion, I wrote the following to test, to get the condition to wait in a test situation. I still get repeated "locked" message. I must be doing something wrong? http://ideone.com/eVuKEC
#include<pthread.h>
#include <iostream>
pthread_mutex_t mutex;
pthread_cond_t cond;
bool something;
void test() {
pthread_mutex_lock(&mutex);
while(!something) {
std::cout <<"locked" << std::endl;
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex);
}
int main(){
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
something=false;
test();
return 0;
}
Upvotes: 0
Views: 127