[Haskell-cafe] STM, orElse and timed read from a channel
Simon Marlow
simonmar at microsoft.com
Tue Nov 29 07:00:03 EST 2005
threadDelay is IO-only; there's no way to use threadDelay in an STM
transaction. For example, if you want to wait for a TVar to go from
Nothing to Just x with a timeout, you could do this:
readOrTimeout :: TVar (Maybe a) -> Int -> STM (Maybe a)
readOrTimeout t secs = do
timeout <- registerTimeout secs
let check_timeout = do
b <- readTVar timeout
if b then return Nothing else retry
check_t = do
m <- readTVar t
case m of
Nothing -> retry
Just x -> return x
atomically $ check_timeout `orElse` check_t
Cheers,
Simon
On 29 November 2005 10:11, Joel Reymont wrote:
> Simon,
>
> How is this easier than just calling threadDelay?
>
> Ideally, I would be looking for something like reading from a TVar
> with a timeout. So that you either get a Nothing (timeout) or the
> value from the TVar. Can I implement it using the GHC timeout thread?
>
> Thanks, Joel
>
> On Nov 29, 2005, at 9:20 AM, Simon Marlow wrote:
>
>> Interestingly, GHC already has a timeout thread - the I/O manager
>> thread handles threadDelay too. It wouldn't be too hard to adapt it
>> to do STM timeouts too, with a function like
>>
>> registerTimeout :: Int -> STM (TVar Bool)
>>
>> and you wait for your timeout by waiting for the TVar to contain
>> True.
More information about the Haskell-Cafe
mailing list