Re: spurious wakeup

From: Marcin 'Qrczak' Kowalczyk (qrczak_at_knm.org.pl)
Date: 11/28/04


Date: Sun, 28 Nov 2004 20:14:13 +0100

Markus.Elfring@web.de (Markus Elfring) writes:

>> The while loop protects against spurious wakeups too. It's not a
>> method, but so what? It can be wrapped in a macro if you insist on
>> a simpler syntax.
>
> You must remember to repeat this loop at all places of the wait call
> if the library's implementation does not offer the suggested
> protection.

There is no substitute to remembering to use the correct API. If he
can forget that waiting should be in a loop, he can as well forget
your template name, or misuse its arguments.

The loop is usually necessary anyway, even without spurious wakeups:

- Another thread may get the mutex between the thread that notified
  about change of the condition, and the thread which was woken up.
  It can cause the condition to become false again.

- If several threads are woken up, it's probable that one of them will
  make the condition false before others have a chance to run, and
  they should wait again.

- It's can be convenient to notify when the condition *might* become
  true when the thread is in a particular place, without precise
  checking of all values of variables which influence the predicate.
  Examples of this were in my elevator sample.

  In general it's the responsibility of the waiting thread to ensure
  that it really wants to proceed. Other threads must only ensure that
  they will not miss any possibility of changing of the predicate,
  but they may notify in more cases than needed: they don't have to
  duplicate the work of checking the predicate precisely.

Thus the fact that waiting is associated wich a predicate which should
be tested in a loop should be taught when the concept of condition
variables is introduced. It is even said in X/Open documentation,
which is not a tutorial but a reference. It's just a part of the
knowledge about how to use condition variables.

I think it's easier to make a bug in emulating a first-class function
in C++, than in forgetting that pthread_cond_wait should be inside
'while' rather than 'if'.

> How big is the probability to forget its application?
> Templates are the safe syntax for a lot of macros.

If you value safety so much, using C++ is a bad idea (lots of
potential undefined behavior out there if you forget about other
things).

-- 
   __("<         Marcin Kowalczyk
   \__/       qrczak@knm.org.pl
    ^^     http://qrnik.knm.org.pl/~qrczak/


Relevant Pages