[Haskell-cafe] Question about takeMVar
Jules Bean
jules at jellybean.co.uk
Thu Nov 29 01:55:51 EST 2007
Maurício wrote:
> Hi,
>
> 'takeMVar' documentation says "if there are
> multiple threads blocked in takeMVar, and the
> MVar becomes full, only one thread will be
> woken up."
>
> Since 'takeMVar' is a reading function, i.e.,
> it doesn't change the value of the
> "variable", why waking up only one thread? If
> we wake multiple threads, there's no risk of
> one changing the value while the other is
> reading.
Why? Because this turns out to be useful primitive.
It is very useful to be able to be sure that only a single thread picks
up a value for all kinds of concurrency styles.
In fact, takeMVar does change the value of the variable: it makes it empty.
> Does that mean that all threads waiting for
> that MVar will get the same value, even if
> one of those threads change it's value just
> after reading?
No, only one thread gets that value. It's a "one time only offer!".
Another thread waiting will get the next value which is 'putMVar'ed.
There are two higher-level constructs, both built from MVars:
readMVar is take followed by put (with a little exception handling) so
that other threads can also get the same value.
A Chan, using the special dupChan facility, gives a stronger guarantee
that each thread reads the same value exactly once. It's something like
a shared queue with multiple readers.
Jules
More information about the Haskell-Cafe
mailing list