X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=Control%2FConcurrent%2FSampleVar.hs;h=ca68a38f76714e7d9d1761411ff68c7e9df4123f;hb=41e8fba828acbae1751628af50849f5352b27873;hp=156940a702f32ac1c39a0af1c6712c068feaa007;hpb=17b054f33fe1ac862a2628b8816ae460428da701;p=ghc-base.git diff --git a/Control/Concurrent/SampleVar.hs b/Control/Concurrent/SampleVar.hs index 156940a..ca68a38 100644 --- a/Control/Concurrent/SampleVar.hs +++ b/Control/Concurrent/SampleVar.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.SampleVar @@ -30,7 +32,13 @@ import Prelude import Control.Concurrent.MVar -import Control.Exception ( block ) +import Control.Exception ( mask_ ) + +import Data.Functor ( (<$>) ) + +import Data.Typeable + +#include "Typeable.h" -- | -- Sample variables are slightly different from a normal 'MVar': @@ -48,28 +56,32 @@ import Control.Exception ( block ) -- * Writing to a filled 'SampleVar' overwrites the current value. -- (different from 'putMVar' on full 'MVar'.) -type SampleVar a - = MVar (Int, -- 1 == full - -- 0 == empty - -- <0 no of readers blocked - MVar a) +newtype SampleVar a = SampleVar ( MVar ( Int -- 1 == full + -- 0 == empty + -- <0 no of readers blocked + , MVar a + ) + ) + deriving (Eq) + +INSTANCE_TYPEABLE1(SampleVar,sampleVarTc,"SampleVar") -- |Build a new, empty, 'SampleVar' newEmptySampleVar :: IO (SampleVar a) newEmptySampleVar = do v <- newEmptyMVar - newMVar (0,v) + SampleVar <$> newMVar (0,v) -- |Build a 'SampleVar' with an initial value. newSampleVar :: a -> IO (SampleVar a) newSampleVar a = do v <- newMVar a - newMVar (1,v) + SampleVar <$> newMVar (1,v) -- |If the SampleVar is full, leave it empty. Otherwise, do nothing. emptySampleVar :: SampleVar a -> IO () -emptySampleVar v = block $ do - s@(readers, var) <- block $ takeMVar v +emptySampleVar (SampleVar v) = mask_ $ do + s@(readers, var) <- takeMVar v if readers > 0 then do _ <- takeMVar var putMVar v (0,var) @@ -78,7 +90,7 @@ emptySampleVar v = block $ do -- |Wait for a value to become available, then take it and return. readSampleVar :: SampleVar a -> IO a -readSampleVar svar = block $ do +readSampleVar (SampleVar svar) = mask_ $ do -- -- filled => make empty and grab sample -- not filled => try to grab value, empty when read val. @@ -91,7 +103,7 @@ readSampleVar svar = block $ do -- |Write a value into the 'SampleVar', overwriting any previous value that -- was there. writeSampleVar :: SampleVar a -> a -> IO () -writeSampleVar svar v = block $ do +writeSampleVar (SampleVar svar) v = mask_ $ do -- -- filled => overwrite -- not filled => fill, write val @@ -114,7 +126,7 @@ writeSampleVar svar v = block $ do -- you see the result of 'isEmptySampleVar'. -- isEmptySampleVar :: SampleVar a -> IO Bool -isEmptySampleVar svar = do +isEmptySampleVar (SampleVar svar) = do (readers, _) <- readMVar svar - return (readers == 0) + return (readers <= 0)