431f709a259273857669de2704c40f6384c78ab5
[ghc-base.git] / System / Timeout.hs
1 -------------------------------------------------------------------------------
2 -- |
3 -- Module      :  System.Timeout
4 -- Copyright   :  (c) The University of Glasgow 2007
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 --
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable
10 --
11 -- Attach a timeout event to arbitrary 'IO' computations.
12 --
13 -------------------------------------------------------------------------------
14
15 #ifdef __GLASGOW_HASKELL__
16 #include "Typeable.h"
17 #endif
18
19 module System.Timeout ( timeout ) where
20
21 #ifdef __GLASGOW_HASKELL__
22 import Prelude             (Show(show), IO, Ord((<)), Eq((==)), Int,
23                             otherwise, fmap)
24 import Data.Maybe          (Maybe(..))
25 import Control.Monad       (Monad(..))
26 import Control.Concurrent  (forkIO, threadDelay, myThreadId, killThread)
27 import Control.Exception   (Exception, handleJust, throwTo, bracket)
28 import Data.Typeable
29 import Data.Unique         (Unique, newUnique)
30
31 -- An internal type that is thrown as a dynamic exception to
32 -- interrupt the running IO computation when the timeout has
33 -- expired.
34
35 data Timeout = Timeout Unique deriving Eq
36 INSTANCE_TYPEABLE0(Timeout,timeoutTc,"Timeout")
37
38 instance Show Timeout where
39     show _ = "<<timeout>>"
40
41 instance Exception Timeout
42 #endif /* !__GLASGOW_HASKELL__ */
43
44 -- |Wrap an 'IO' computation to time out and return @Nothing@ in case no result
45 -- is available within @n@ microseconds (@1\/10^6@ seconds). In case a result
46 -- is available before the timeout expires, @Just a@ is returned. A negative
47 -- timeout interval means \"wait indefinitely\". When specifying long timeouts,
48 -- be careful not to exceed @maxBound :: Int@.
49 --
50 -- The design of this combinator was guided by the objective that @timeout n f@
51 -- should behave exactly the same as @f@ as long as @f@ doesn't time out. This
52 -- means that @f@ has the same 'myThreadId' it would have without the timeout
53 -- wrapper. Any exceptions @f@ might throw cancel the timeout and propagate
54 -- further up. It also possible for @f@ to receive exceptions thrown to it by
55 -- another thread.
56 --
57 -- A tricky implementation detail is the question of how to abort an @IO@
58 -- computation. This combinator relies on asynchronous exceptions internally.
59 -- The technique works very well for computations executing inside of the
60 -- Haskell runtime system, but it doesn't work at all for non-Haskell code.
61 -- Foreign function calls, for example, cannot be timed out with this
62 -- combinator simply because an arbitrary C function cannot receive
63 -- asynchronous exceptions. When @timeout@ is used to wrap an FFI call that
64 -- blocks, no timeout event can be delivered until the FFI call returns, which
65 -- pretty much negates the purpose of the combinator. In practice, however,
66 -- this limitation is less severe than it may sound. Standard I\/O functions
67 -- like 'System.IO.hGetBuf', 'System.IO.hPutBuf', Network.Socket.accept, or
68 -- 'System.IO.hWaitForInput' appear to be blocking, but they really don't
69 -- because the runtime system uses scheduling mechanisms like @select(2)@ to
70 -- perform asynchronous I\/O, so it is possible to interrupt standard socket
71 -- I\/O or file I\/O using this combinator.
72
73 timeout :: Int -> IO a -> IO (Maybe a)
74 #ifdef __GLASGOW_HASKELL__
75 timeout n f
76     | n <  0    = fmap Just f
77     | n == 0    = return Nothing
78     | otherwise = do
79         pid <- myThreadId
80         ex  <- fmap Timeout newUnique
81         handleJust (\e -> if e == ex then Just () else Nothing)
82                    (\_ -> return Nothing)
83                    (bracket (forkIO (threadDelay n >> throwTo pid ex))
84                             (killThread)
85                             (\_ -> fmap Just f))
86 #else
87 timeout n f = fmap Just f
88 #endif /* !__GLASGOW_HASKELL__ */