Mutex: Difference between revisions
Content added Content deleted
(Added an explaination of Haskell's MVars.) |
|||
Line 343: | Line 343: | ||
}</lang> |
}</lang> |
||
The value passed on the channel is not accessed here, just as the internal state of a mutex is not accessed. Rather, it is only the effect of the value being available that is important. (Of course if you wanted to send something meaningful on the channel, a reference to the shared resource would be a good start...) |
The value passed on the channel is not accessed here, just as the internal state of a mutex is not accessed. Rather, it is only the effect of the value being available that is important. (Of course if you wanted to send something meaningful on the channel, a reference to the shared resource would be a good start...) |
||
=={{header|Haskell}}== |
|||
Haskell has a slight variation on the mutex, namely the MVar. MVars, unlike mutexes, are containers. However, they are similar enough that MVar () is essentially a mutex. A MVar can be in two states: empty or full, only storing a value when full. There are 4 main ways to deal with MVars: |
|||
<lang haskell>takeMVar :: MVar a -> IO a |
|||
putMVar :: MVar a -> a -> IO () |
|||
tryTakeMVar :: MVar a -> IO (Maybe a) |
|||
tryPutMVar :: MVar a -> a -> IO Bool |
|||
</lang> |
|||
takeMVar will attempt to fetch a value from the MVar, and will block while the MVar is empty. After using this, the MVar will be left empty. |
|||
putMVar will attempt to put a value in a MVar, and will block while there already is a value in the MVar. This will leave the MVar full. |
|||
The last two functions are non-blocking versions of takeMVar and putMVar, returning Nothing and False, respectively, if their blocking counterpart would have blocked. |
|||
For more information see the [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html documentation]. |
|||
==Icon and {{header|Unicon}}== |
==Icon and {{header|Unicon}}== |