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)
@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