RE: [Haskell-cafe] STM, orElse and timed read from a channel

On 29 November 2005 06:29, Tomasz Zielonka wrote:
On Mon, Nov 28, 2005 at 11:27:46PM +0000, Joel Reymont wrote:
Folks,
How would you implement a timed read from a channel with STM? I would like to return Timeout if nothing was read from a TChan in X ms.
Is this a basic two-thread timeout implementation or is there a more elegant way of implementing this using `orElse`?
Here is a basic two-thread implementation:
http://www.haskell.org/pipermail/haskell-cafe/2005-January/008303.html
The other approach I see is to create a TVar that would be updated with current time every 0.1 s (or something like that), but that would be rather inefficient.
You could also create a time-out manager thread (with a priority queue, etc), so you don't have to spawn a thread for every timeout.
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. Cheers, Simon

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.
participants (2)
-
Joel Reymont
-
Simon Marlow