-- | Perform an IO action, and place its result in an 'MVar'.  See
-- also "Control.Concurrent.STM.TMVarIO" for a 'TMVar' version.
module Control.Concurrent.MVarIO (run) where

import Control.Concurrent

-- | @'run' action@ returns an 'MVar' immediately. The result of
-- @action@ will be placed in said 'MVar'. If the 'MVar' is full when
-- @action@ completes, the return value is lost (the action does not
-- wait for an empty 'MVar').
run :: IO a -> IO (MVar a)
run action = newEmptyMVar >>= \mv ->
             forkIO (run' action mv) >>
             return mv

run' :: IO a -> MVar a -> IO ()
run' action mv = action >>= \ret ->
                 tryPutMVar mv ret >>
                 return ()