Fix some "warn-unused-do-bind" warnings where we want to ignore the value
[ghc-base.git] / Control / Concurrent / SampleVar.hs
index ccb93e1..a76346f 100644 (file)
 
 module Control.Concurrent.SampleVar
        (
-        -- * Sample Variables
+         -- * Sample Variables
          SampleVar,         -- :: type _ =
  
-        newEmptySampleVar, -- :: IO (SampleVar a)
+         newEmptySampleVar, -- :: IO (SampleVar a)
          newSampleVar,      -- :: a -> IO (SampleVar a)
-        emptySampleVar,    -- :: SampleVar a -> IO ()
-        readSampleVar,     -- :: SampleVar a -> IO a
-        writeSampleVar     -- :: SampleVar a -> a -> IO ()
+         emptySampleVar,    -- :: SampleVar a -> IO ()
+         readSampleVar,     -- :: SampleVar a -> IO a
+         writeSampleVar,    -- :: SampleVar a -> a -> IO ()
+         isEmptySampleVar,  -- :: SampleVar a -> IO Bool
 
        ) where
 
@@ -46,9 +47,9 @@ import Control.Concurrent.MVar
 --    (different from 'putMVar' on full 'MVar'.)
 
 type SampleVar a
- = MVar (Int,          -- 1  == full
-                       -- 0  == empty
-                       -- <0 no of readers blocked
+ = MVar (Int,           -- 1  == full
+                        -- 0  == empty
+                        -- <0 no of readers blocked
           MVar a)
 
 -- |Build a new, empty, 'SampleVar'
@@ -60,15 +61,15 @@ newEmptySampleVar = do
 -- |Build a 'SampleVar' with an initial value.
 newSampleVar :: a -> IO (SampleVar a)
 newSampleVar a = do
-   v <- newEmptyMVar
-   putMVar v a
+   v <- newMVar a
    newMVar (1,v)
 
 -- |If the SampleVar is full, leave it empty.  Otherwise, do nothing.
 emptySampleVar :: SampleVar a -> IO ()
 emptySampleVar v = do
    (readers, var) <- takeMVar v
-   if readers >= 0 then
+   if readers > 0 then do
+     _ <- takeMVar var
      putMVar v (0,var)
     else
      putMVar v (readers,var)
@@ -100,3 +101,16 @@ writeSampleVar svar v = do
      _ -> 
        putMVar val v >> 
        putMVar svar (min 1 (readers+1), val)
+
+-- | Returns 'True' if the 'SampleVar' is currently empty.
+--
+-- Note that this function is only useful if you know that no other
+-- threads can be modifying the state of the 'SampleVar', because
+-- otherwise the state of the 'SampleVar' may have changed by the time
+-- you see the result of 'isEmptySampleVar'.
+--
+isEmptySampleVar :: SampleVar a -> IO Bool
+isEmptySampleVar svar = do
+   (readers, _) <- readMVar svar
+   return (readers == 0)
+