on aa2b166 help sign in
50 lines 1.6 kB history raw
1{-# LANGUAGE UnboxedTuples #-}
3-- |
4-- Module : Streamly.Internal.Control.ForkIO
5-- Copyright : (c) 2017 Composewell Technologies
6-- License : BSD-3-Clause
7-- Maintainer : streamly@composewell.com
8-- Stability : experimental
9-- Portability : GHC
11module Streamly.Internal.Control.ForkIO
12 ( rawForkIO
13 , forkIOManaged
14 , forkManagedWith
15 )
16where
18import Control.Concurrent (ThreadId, forkIO, killThread)
19import Control.Monad.IO.Class (MonadIO(..))
20import GHC.Conc (ThreadId(..))
21import GHC.Exts
22import GHC.IO (IO(..))
23import System.Mem.Weak (addFinalizer)
25-- | Stolen from the async package. The perf improvement is modest, 2% on a
26-- thread heavy benchmark (parallel composition using noop computations).
27-- A version of forkIO that does not include the outer exception
28-- handler: saves a bit of time when we will be installing our own
29-- exception handler.
30{-# INLINE rawForkIO #-}
31rawForkIO :: IO () -> IO ThreadId
32rawForkIO (IO action) = IO $ \ s ->
33 case fork# action s of (# s1, tid #) -> (# s1, ThreadId tid #)
35-- | Fork a thread that is automatically killed as soon as the reference to the
36-- returned threadId is garbage collected.
37--
38{-# INLINABLE forkManagedWith #-}
39forkManagedWith :: MonadIO m => (m () -> m ThreadId) -> m () -> m ThreadId
40forkManagedWith fork action = do
41 tid <- fork action
42 liftIO $ addFinalizer tid (killThread tid)
43 return tid
45-- | Fork a thread that is automatically killed as soon as the reference to the
46-- returned threadId is garbage collected.
47--
48{-# INLINABLE forkIOManaged #-}
49forkIOManaged :: IO () -> IO ThreadId
50forkIOManaged = forkManagedWith forkIO