Advertisement
gatoatigrado3

forkos_try example

Feb 29th, 2012
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Control.Exception
  2. import Control.Monad
  3. import Control.Concurrent
  4. import Control.Concurrent.MVar
  5.  
  6. import Data.IORef
  7.  
  8. import Text.Printf
  9.  
  10.  
  11. -- | Takes a command x and continuation rest;
  12. -- if x is (Just y), passes (Just y) to the continuation
  13. -- otherwise, rolls back state and passes Nothing to the continuation
  14. forkos_try :: IO (Maybe α) -> (Maybe α -> IO ()) -> IO ()
  15. forkos_try x rest = do
  16.     mv <- newEmptyMVar :: IO (MVar Bool)
  17.     forkOS (do
  18.         v <- x
  19.         case v of
  20.             Nothing -> putMVar mv False >> throw ThreadKilled
  21.             (Just _) -> putMVar mv True >> rest v)
  22.     v <- takeMVar mv
  23.     if v then return () else rest Nothing
  24.  
  25. -- Mock function that does some imperative operation,
  26. -- which may succeed or fail.
  27. decrement :: IORef Int -> IO (Maybe ())
  28. decrement x = do
  29.     xv <- readIORef x
  30.     -- IMPORTANT -- messes up state during calculation
  31.     writeIORef x (-100000)
  32.  
  33.     if (xv > 0) then do
  34.         writeIORef x (xv - 1)
  35.         return (Just ())
  36.     else
  37.         return Nothing
  38.  
  39. main = do
  40.     x <- newIORef (3 :: Int)
  41.     -- NOTE: If this looks scary, just mentally remove the "$ \_ -> do" parts,
  42.     -- and de-indent all following lines.
  43.     forkos_try (decrement x) $ \_ -> do
  44.         forkos_try (decrement x) $ \_ -> do
  45.             forkos_try (decrement x) $ \_ -> do
  46.                 forkos_try (decrement x) $ \_ -> do
  47.                     mytid <- myThreadId
  48.                     putStrLn $ printf "final thread ID: %s" (show mytid)
  49.                     xv <- readIORef x
  50.                     putStrLn $ printf "value of x: %d" xv
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement