[prev in list] [next in list] [prev in thread] [next in thread] 

List:       haskell-cafe
Subject:    RE: [Haskell-cafe] How to use QSem?
From:       "Simon Marlow" <simonmar () microsoft ! com>
Date:       2004-06-23 9:56:04
Message-ID: 3429668D0E777A499EE74A7952C382D10207B937 () EUR-MSG-01 ! europe ! corp ! microsoft ! com
[Download RAW message or body]

On 22 June 2004 21:44, S. Alexander Jacobson wrote:

> The GHC documentation on QSem is very sparse.  I
> would like to give a thread exclusive access to a
> resource.
> 
> My *guess* based on the documentation is that I
> can create an exclusive lock using:
> 
>    logSem <- newQSem 1

If the maximum value of your QSem is 1, then an MVar will do.  That is,
an MVar can be used as a simple semaphore, and a QSem is necessary if
you need a quantity semaphore (there are > 1 units of the resource).

> And then any thread that wants to lock the
> resource uses:
> 
>    withLogSem x = do waitQSem logSem; y <- x; signalQSem logSem;
> return y 
> 
> as follows:
> 
>    withLogSem $ rotate curLogPos

import Control.Concurrent, create the semaphore like this:

   m <- newMVar ()

and use it like this:

   withMVar m $ \_ -> ... critical section ...

If you are using the semaphore to protect a mutable variable, then you
can handily merge the two ideas into an MVar, which behaves like a
thread-safe mutable variable.

Cheers,
	Simon

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic