SHARE
TWEET

Using MVar to add actions to Threads

philipjf Sep 12th, 2012 48 Never
  1. import Control.Concurrent
  2. import Control.Concurrent.MVar
  3. import Control.Monad
  4.  
  5. data ExtendableThread = ExtendableThread {
  6.    toDo     :: MVar (IO ()),
  7.    threadId :: ThreadId
  8.   }
  9.  
  10. forkIOExtendable t
  11.    = do var <- newEmptyMVar
  12.         let cleanup = takeMVar var >>= (>> cleanup)
  13.         id <- forkIO (t >> cleanup)
  14.         return $ ExtendableThread {toDo = var, threadId = id}
  15.  
  16. --blocking
  17. addAction thread act = putMVar (toDo thread) act
  18.  
  19. --non blocking
  20. addAction' t a = (forkIO (addAction t a)) >> return ()
  21.  
  22. --demonstration
  23. main = do t <- forkIOExtendable $ putStrLn "hello"
  24.           addAction' t $ putStrLn "world"
  25.           addAction' t $ putStrLn "another line"
RAW Paste Data
Top