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

Simon Marlow simonmar at microsoft.com
Tue Nov 29 04:20:40 EST 2005


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


More information about the Haskell-Cafe mailing list