23
23
24
24
{-# LANGUAGE Trustworthy #-}
25
25
{-# LANGUAGE RecursiveDo #-}
26
- {-# LANGUAGE DeriveDataTypeable #-}
27
26
28
27
module Control.Timeout
29
28
( NominalDiffTime
@@ -33,30 +32,18 @@ module Control.Timeout
33
32
, sleep
34
33
) where
35
34
36
- import Control.Exception (Exception )
37
- import Control.Concurrent (myThreadId , forkIO , killThread , threadDelay , throwTo ,
35
+ import Control.Concurrent (myThreadId , forkIO , killThread , throwTo ,
38
36
rtsSupportsBoundThreads )
39
- import Data.Typeable (Typeable )
40
37
import Data.Time.Clock (NominalDiffTime )
41
38
import Data.Unique (newUnique )
42
- import GHC.Event (TimeoutKey , getSystemTimerManager , registerTimeout , unregisterTimeout )
39
+ import GHC.Event (getSystemTimerManager , registerTimeout , unregisterTimeout )
43
40
import Unsafe.Coerce (unsafeCoerce )
44
41
45
42
import Control.Monad.Catch (MonadCatch (.. ), bracket , handleJust )
46
43
import Control.Monad.Trans (MonadIO , liftIO )
47
44
48
- -- | Exception used for timeout handling
49
- newtype Timeout = Timeout TimeoutKey
50
- deriving (Eq , Typeable )
51
-
52
- instance Show Timeout where
53
- show _ = " <<timeout>>"
54
-
55
- instance Exception Timeout
56
-
57
- timeToUsecs :: NominalDiffTime -> Int
58
- timeToUsecs t = floor $ (* 1000000 ) $ toRational t
59
- {-# INLINEABLE timeToUsecs #-}
45
+ import Control.Timeout.EventManager.Types
46
+ import Control.Timeout.Utils
60
47
61
48
-- | Wrap an 'MonadIO' computation to time out and return @Nothing@ in case no result
62
49
-- is available within @n@ seconds. In case a result
@@ -94,11 +81,11 @@ withTimeout t f | t <= 0 = return Nothing
94
81
timer <- liftIO getSystemTimerManager
95
82
ex@ (Timeout key) <- liftIO $ mdo
96
83
pid <- liftIO myThreadId
97
- ex <- return . Timeout =<< (liftIO $ registerTimeout timer (timeToUsecs t) (throwTo pid ex))
84
+ ex <- fmap ( Timeout . unsafeCoerce) (liftIO $ registerTimeout timer (timeToUsecs t) (throwTo pid ex))
98
85
return ex
99
86
handleJust (\ e -> if e == ex then Just () else Nothing )
100
87
(\ _ -> return Nothing )
101
- (f ex >>= \ r -> (liftIO $ unregisterTimeout timer key) >> (return $ Just r))
88
+ (f ex >>= \ r -> (liftIO $ unregisterTimeout timer (unsafeCoerce key) ) >> (return $ Just r))
102
89
| otherwise = do
103
90
pid <- liftIO myThreadId
104
91
ex <- liftIO newUnique >>= return . Timeout . unsafeCoerce
@@ -107,9 +94,3 @@ withTimeout t f | t <= 0 = return Nothing
107
94
(bracket (liftIO $ forkIO (sleep t >> throwTo pid ex))
108
95
(liftIO . killThread)
109
96
(\ _ -> f ex >>= return . Just ))
110
-
111
- -- | Sleep for 'NominalDiffTime', example:
112
- --
113
- -- > sleep 5 -- Will sleep for 5 seconds
114
- sleep :: (MonadIO m ) => NominalDiffTime -> m ()
115
- sleep = liftIO . threadDelay . timeToUsecs
0 commit comments