implement conditional variable wait() - atmoic unlock+sleep?

31 views Asked by At

I'm trying to figure out an implementation of conditional variable:

// suppose there is an internal wait_queue for threads to block on this cv.
void wait(Mutex mtx) {
  enqueue(wait_queue, current_thread);
  
  mtx.unlock();
  // notify() kicks in?
  sleep();

  // lock again after waken up.
  mtx.lock();
}

void notify() {
  wait_thread = dequeue(wait_queue);
  wake_up(wait_thread);
}

As the pseudo-code implies, it first added current thread to the cv internal wait queue, then released the external mutex and went to sleeping status.

My question is what if notify() kicked in before sleep(), and tried to wake up the waiting thread which had not yet truely be in sleep (so this wake_up() will be an no-op?), and then context switched back to sleep(). Will the wait thread then block forever?

In other words, is there an atmoic [mutex.unlock() + sleep()] operation at the system level, to make sure wake_up() can't kick in before sleep()?

0

There are 0 answers