
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. 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? Thanks, Maurício

'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.
Also in the docs: After a takeMVar, the MVar is left empty. The behaviour you describe is more like readMVar. Because readMVar does a takeMVar followed by a putMVar, it will wake up multiple threads. If you want to broadcast to multiple threads, you might also want to consider dupChan in Control.Concurrent.Chan.

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
participants (4)
-
Bulat Ziganshin
-
Jules Bean
-
Matthew Brecknell
-
Maurício