Want more features on Pastebin? Sign Up, it's FREE!
Guest

Using MVar to add actions to Threads

By: philipjf on Sep 12th, 2012  |  syntax: Haskell  |  size: 0.68 KB  |  views: 45  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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"
clone this paste RAW Paste Data