Re: How to wait for multiple threads simultaneously?



David Schwartz <davids@xxxxxxxxxxxxx> writes:
On Feb 13, 11:53 pm, Rainer Weikusat <rweiku...@xxxxxxxxxxx> wrote:
But they typically don't loop until something happens. This is just a
special case the code needs to be prepared for, while it is the exact
behaviour of a spin lock.

I think that's based on the mistaken assumption that the only reason
the loop would run more than once is in the rare case where there's a
spurious wakeup.

The assumption is not mistaken. The purpose of a condition variable is
roughly the same as that of a wait queue in the kernel: Enable some
set of threads to block until woken up by another thread. In contrast
to this, a spin lock is something which does not cause a thread trying
to acquire it to block if the lock is already taken, but to 'spin', ie
continue trying to acquire the lock, until that succeeds. This
difference in behaviour is the exact reason why it is called a spin
lock and using the term this way is common in literature.

But that's not true. One common reason you would loop on a
pthread_cond_wait is when the condition may have been consumed by
other threads.

And this actually nicely illustrates why using established terms to
express different meanings is a bad idea: Your idea of a condition
variable is quite obviously not something which causes a thread to
sleep until woken up, but some basically purposeless addition to a
loop which is busy-waiting until some condition is true.

That is, spinning is part of the normal synchronization process. It's
not just a workaround for a bizarre side-effect.

The loop around the test is part of the normal usage of a condition
variable, because the fact that the thread has been woken up is not
supposed to implicitly communicate something about the state of the
predicate. Apart from that, the cutesy name for the condition you
describe would be 'the thundering herd problem' and Pthreads provide
interfaces to avoid that (pthread_cond_signal instead of
pthread_cond_broadcast).
.



Relevant Pages