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
|
2012-06-29 03:40:16 +00:00
|
|
|
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
|
2012-06-29 03:40:16 +00:00
|
|
|
runThreadState mvar a = modifyMVar mvar $ \state -> swap <$> Annex.run state a
|