1

i have a problem with boost condition, i have these two instance variable within a cpp class:

boost::condition          wait_answer_condition;
boost::mutex              wait_answer_mutex;

then i have a method that send a message and with on condition:

method1

boost::unique_lock<boost::mutex>  lock(wait_answer_mutex)

//do some work and send message

//wait the result
wait_answer_condition.wait(lk);

//get the result
result = responseIdSyncMap[currentRequestID];

then i have another method that receive the result and wakeup the sender thread

method2

int requestID = responseData->getInt32Value("response_id");
responseIdSyncMap.insert(make_pair(requestID, responseData));
wait_answer_condition.notify_one();

the two method are called in different thread. The problem is that when the method2 is called the wait_answer_condition is release before "wait_answer_condition.notify_one()" is called, and the method1 is awaked without found the result.

Anyone has an idea about that?

tuergeist
  • 9,171
  • 3
  • 37
  • 58
Macdeveloper
  • 91
  • 1
  • 8
  • according to http://www.boost.org/doc/libs/1_48_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref I think this behavior is intended - you forgot to lock out the threads – tuergeist Jan 27 '12 at 13:10
  • Also with th lock i had sam result. The reazione of that is the spuriously behavior of wait condition. See the thiton answer. – Macdeveloper Jan 28 '12 at 08:10

1 Answers1

4

Condition variables can wake up spuriously, and wake-up events are generally not stored (i.e. a wake-up that is issued before anyone is waiting for it is lost like a handclap in a wood when noone is there to hear). Therefore, condition variables are almost always used in a loop:

bool is_answered = false;

// method1
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
while ( ! is_answered )
    wait_answer_condition.wait(lock);

// method2
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
is_answered = true;
wait_answer_condition.notify_one();
thiton
  • 35,651
  • 4
  • 70
  • 100
  • I would rephrase your last sentence to "Therefore, condition variables should always be used in a loop", see also (not boost) http://stackoverflow.com/questions/5536759/condition-variable-why-calling-pthread-cond-signal-before-calling-pthread-co/5538447#5538447 – stefaanv Jan 27 '12 at 13:26