git-annex/Assistant/ThreadedMonad.hs

50 lines
1.4 KiB
Haskell
Raw Normal View History

2012-06-13 16:36:33 +00:00
{- making the Annex monad available across threads
-
- Copyright 2012 Joey Hess <joey@kitenet.net>
2012-06-23 05:20:40 +00:00
-
- Licensed under the GNU GPL version 3 or higher.
2012-06-13 16:36:33 +00:00
-}
module Assistant.ThreadedMonad where
import Common.Annex
import qualified Annex
import Control.Concurrent
import Data.Tuple
2012-06-13 16:36:33 +00:00
{- 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.
-
2012-06-22 17:39:44 +00:00
- This serializes calls by threads; only one thread can run in Annex at a
- time. -}
2012-06-13 16:36:33 +00:00
runThreadState :: ThreadState -> Annex a -> IO a
runThreadState mvar a = modifyMVar mvar $ \state -> swap <$> Annex.run state a
{- Runs an Annex action, using a copy of the state from the MVar.
-
- It's up to the action to perform any necessary shutdown tasks in order
- for state to not be lost. And it's up to the caller to resynchronise
- with any changes the action makes to eg, the git-annex branch.
-}
unsafeRunThreadState :: ThreadState -> Annex a -> IO ()
unsafeRunThreadState mvar a = do
state <- readMVar mvar
void $ Annex.eval state a