Skip to content

Instantly share code, notes, and snippets.

@robstewart57
Created December 3, 2012 13:28
Show Gist options
  • Save robstewart57/4195051 to your computer and use it in GitHub Desktop.
Save robstewart57/4195051 to your computer and use it in GitHub Desktop.
Timeouts in async haskell package
{-# LANGUAGE DeriveDataTypeable #-}
import Control.Concurrent (threadDelay)
import Control.Exception (Exception,throw)
import Control.Monad (void)
import Control.Concurrent.Async (Async,race,wait,withAsync)
import Data.Typeable (Typeable)
data ThreadTimeoutException = ThreadTimeoutException
deriving (Show, Typeable)
instance Exception ThreadTimeoutException
waitTimeout :: Async a -> Int -> IO (Either ThreadTimeoutException a)
waitTimeout t i =
race (threadDelay i >> throw ThreadTimeoutException) (wait t)
asyncTimeout_ :: IO a -> Int -> IO ()
asyncTimeout_ f i =
withAsync f $ \a1 ->
withAsync (threadDelay i) $ \a2 ->
void $ race (wait a1) (wait a2)
@joehealy
Copy link

Should line 14 be return ThreadTimeoutException rather throw?

@joe9
Copy link

joe9 commented Jul 10, 2017

added a package for AsyncTimeouts.hs https://github.com/joe9/async-timeouts

@Qiu233
Copy link

Qiu233 commented May 8, 2023

This should be simplified by returning a Maybe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment