The execution sequence after conditional variable notify

145 Views Asked by At

There are two threads (Call them T1 and T2) that sync with each other by boost condition variable and mutex like:

boost::condition_variable global_cond;
boost::mutex global_mutex;
boost::unique_lock<boost::mutex> lock( global_mutex);

thread1() {
  global_cond.notify_one();
  code_block_a();
}

tread2() {
  global_cond.wait(lock)
  code_block_b();
}

Let's say I can gugarntee that thread2 come to wait first and then thread1 will do the notify.

My question is, is that determinastic that code_block_a() or code_block_b() will execute first?

1

There are 1 best solutions below

0
Roman On

Not guaranteed. The system may perform context switching right after thread1 called notify_one() and allow thread2() to run. And it may not.

Please note that your code is generally buggy because global_cond.wait(lock) can be spuriously woken up and tread2 can run code_block_b() even before thread1() has run.