Advertisement
philipjf

Using MVar to add actions to Threads

Sep 12th, 2012
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement