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
|
2012-07-05 22:07:49 +00:00
|
|
|
|
2012-07-18 23:13:56 +00:00
|
|
|
{- Runs an Annex action, using a copy of the state from the MVar.
|
2012-07-05 22:07:49 +00:00
|
|
|
-
|
2012-07-07 00:48:51 +00:00
|
|
|
- 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.
|
2012-07-05 22:07:49 +00:00
|
|
|
-}
|
2012-07-18 23:13:56 +00:00
|
|
|
unsafeRunThreadState :: ThreadState -> Annex a -> IO ()
|
|
|
|
unsafeRunThreadState mvar a = do
|
2012-07-05 22:07:49 +00:00
|
|
|
state <- readMVar mvar
|
2012-07-18 23:13:56 +00:00
|
|
|
void $ Annex.eval state a
|