SampleVar semantics

Eric Stansifer eric.stansifer+haskell at gmail.com
Sun Jan 2 02:03:41 CET 2011


Hi,

I didn't get a response to my question on haskell-cafe, perhaps
libraries is a more appropriate place to ask.


doc:  http://www.haskell.org/ghc/docs/7.0-latest/html/libraries/base-4.3.0.0/Control-Concurrent-SampleVar.html
source:  http://www.haskell.org/ghc/docs/7.0-latest/html/libraries/base-4.3.0.0/src/Control-Concurrent-SampleVar.html

The isEmptySampleVar function,

isEmptySampleVar :: SampleVar a -> IO Bool
isEmptySampleVar (SampleVar svar) = do
  (readers, _) <- readMVar svar
  return (readers == 0)

returns False whenever readers < 0.  However, readers < 0 occurs when
there are threads waiting on an empty SampleVar.

The documentation on SampleVar is a bit sparse on explaining the
intended behavior;  I wouldn't have expected this behavior if I hadn't
read the source.  Can someone clarify the semantics of SampleVar?

For a contrived example, consider


do_something = threadDelay 100000     -- 100 ms

produce, consume :: SampleVar Int -> IO ()
produce svar = do
    do_something
    b <- isEmptySampleVar svar
    if b then    randomIO >>= writeSampleVar svar    else   return ()
    produce svar

consume svar = do
    x <- readSampleVar svar
    print x
    consume svar

main = do
    svar <- newEmptySampleVar
    forkIO $ produce svar
    forkIO $ consume svar
    threadDelay 1000000       -- one second

This code deadlocks instead of printing random numbers.

Thanks,
Eric



More information about the Libraries mailing list