on e01057f help sign in
53 lines 1.7 kB history raw
1-- |
2-- Module : Streamly.Internal.Control.ForkLifted
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
7-- Portability : GHC
9module Streamly.Internal.Control.ForkLifted
10 (
11 doFork
12 , fork
13 , forkManaged
14 )
15where
17import Control.Concurrent (ThreadId, forkIO)
18import Control.Exception (SomeException(..), catch, mask)
19import Data.Functor (void)
20import Streamly.Internal.Control.Concurrent (MonadRunInIO, RunInIO(..), withRunInIO, withRunInIONoRestore)
21import Streamly.Internal.Control.ForkIO (rawForkIO, forkManagedWith)
23-- | Fork a thread to run the given computation, installing the provided
24-- exception handler. Lifted to any monad with 'MonadRunInIO m'
25-- capability.
26--
27-- TODO: the RunInIO argument can be removed, we can directly pass the action
28-- as "mrun action" instead.
29{-# INLINE doFork #-}
30doFork :: MonadRunInIO m
31 => m ()
32 -> RunInIO m
33 -> (SomeException -> IO ())
34 -> m ThreadId
35doFork action (RunInIO mrun) exHandler =
36 withRunInIO $ \run ->
37 mask $ \restore -> do
38 tid <- rawForkIO $ catch (restore $ void $ mrun action)
39 exHandler
40 run (return tid)
42-- | 'fork' lifted to any monad with 'MonadBaseControl IO m' capability.
43--
44{-# INLINABLE fork #-}
45fork :: MonadRunInIO m => m () -> m ThreadId
46fork m = withRunInIONoRestore $ \run -> forkIO $ void $ run m
48-- | Fork a thread that is automatically killed as soon as the reference to the
49-- returned threadId is garbage collected.
50--
51{-# INLINABLE forkManaged #-}
52forkManaged :: MonadRunInIO m => m () -> m ThreadId
53forkManaged = forkManagedWith fork