SampleVar semantics

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


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


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
    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.


More information about the Libraries mailing list