summaryrefslogtreecommitdiff
path: root/Assistant/Types/ThreadedMonad.hs
diff options
context:
space:
mode:
authorGravatar Joey Hess <joey@kitenet.net>2012-10-29 19:07:10 -0400
committerGravatar Joey Hess <joey@kitenet.net>2012-10-29 19:07:10 -0400
commit86b3857a4c1edafef817935ad3c5d63e6d2d3b25 (patch)
tree119204ef14b23c9b3d99b19888f4a63e8157d702 /Assistant/Types/ThreadedMonad.hs
parenta23b5c6e324068108043a999bb816379ec417bf2 (diff)
moved ThreadedMonad to Types
Diffstat (limited to 'Assistant/Types/ThreadedMonad.hs')
-rw-r--r--Assistant/Types/ThreadedMonad.hs38
1 files changed, 38 insertions, 0 deletions
diff --git a/Assistant/Types/ThreadedMonad.hs b/Assistant/Types/ThreadedMonad.hs
new file mode 100644
index 000000000..1a2aa7eb7
--- /dev/null
+++ b/Assistant/Types/ThreadedMonad.hs
@@ -0,0 +1,38 @@
+{- making the Annex monad available across threads
+ -
+ - Copyright 2012 Joey Hess <joey@kitenet.net>
+ -
+ - Licensed under the GNU GPL version 3 or higher.
+ -}
+
+module Assistant.Types.ThreadedMonad where
+
+import Common.Annex
+import qualified Annex
+
+import Control.Concurrent
+import Data.Tuple
+
+{- The Annex state is stored in a MVar, so that threaded actions can access
+ - it. -}
+type ThreadState = MVar Annex.AnnexState
+
+{- Stores the Annex state in a MVar.
+ -
+ - Once the action is finished, retrieves the state from the MVar.
+ -}
+withThreadState :: (ThreadState -> Annex a) -> Annex a
+withThreadState a = do
+ state <- Annex.getState id
+ mvar <- liftIO $ newMVar state
+ r <- a mvar
+ newstate <- liftIO $ takeMVar mvar
+ Annex.changeState (const newstate)
+ return r
+
+{- Runs an Annex action, using the state from the MVar.
+ -
+ - This serializes calls by threads; only one thread can run in Annex at a
+ - time. -}
+runThreadState :: ThreadState -> Annex a -> IO a
+runThreadState mvar a = modifyMVar mvar $ \state -> swap <$> Annex.run state a