2012-06-13 12:36:33 -04:00
|
|
|
{- making the Annex monad available across threads
|
|
|
|
-
|
|
|
|
- Copyright 2012 Joey Hess <joey@kitenet.net>
|
2012-06-23 01:20:40 -04:00
|
|
|
-
|
|
|
|
- Licensed under the GNU GPL version 3 or higher.
|
2012-06-13 12:36:33 -04:00
|
|
|
-}
|
|
|
|
|
|
|
|
module Assistant.ThreadedMonad where
|
|
|
|
|
|
|
|
import Common.Annex
|
|
|
|
import qualified Annex
|
|
|
|
|
|
|
|
import Control.Concurrent
|
2012-06-28 23:40:16 -04:00
|
|
|
import Data.Tuple
|
2012-06-13 12:36:33 -04: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 13:39:44 -04:00
|
|
|
- This serializes calls by threads; only one thread can run in Annex at a
|
|
|
|
- time. -}
|
2012-06-13 12:36:33 -04:00
|
|
|
runThreadState :: ThreadState -> Annex a -> IO a
|
2012-06-28 23:40:16 -04:00
|
|
|
runThreadState mvar a = modifyMVar mvar $ \state -> swap <$> Annex.run state a
|
2012-07-05 16:07:49 -06:00
|
|
|
|
2012-07-18 19:13:56 -04:00
|
|
|
{- Runs an Annex action, using a copy of the state from the MVar.
|
2012-07-05 16:07:49 -06:00
|
|
|
-
|
2012-07-06 18:48:51 -06: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 16:07:49 -06:00
|
|
|
-}
|
2012-07-18 19:13:56 -04:00
|
|
|
unsafeRunThreadState :: ThreadState -> Annex a -> IO ()
|
|
|
|
unsafeRunThreadState mvar a = do
|
2012-07-05 16:07:49 -06:00
|
|
|
state <- readMVar mvar
|
2012-07-18 19:13:56 -04:00
|
|
|
void $ Annex.eval state a
|