@@ -10,13 +10,16 @@ module Simplex.Messaging.Agent.Lock
1010 )
1111where
1212
13+ import Control.Concurrent (myThreadId )
1314import Control.Monad (void )
1415import Control.Monad.Except (ExceptT (.. ), runExceptT )
1516import Control.Monad.IO.Unlift
1617import Data.Functor (($>) )
1718import Data.Set (Set )
1819import qualified Data.Set as S
1920import Data.Text (Text )
21+ import qualified Data.Text as T
22+ import Debug.Trace (traceIO )
2023import UnliftIO.Async (forConcurrently )
2124import qualified UnliftIO.Exception as E
2225import UnliftIO.STM
@@ -44,15 +47,30 @@ withLock' lock name =
4447withGetLock :: MonadUnliftIO m => (k -> STM Lock ) -> k -> Text -> m a -> m a
4548withGetLock getLock key name a =
4649 E. bracket
47- (atomically $ getPutLock getLock key name)
48- (atomically . takeTMVar)
50+ (do liftIO $ do
51+ tid <- myThreadId
52+ traceIO $ " LOCK acquire " <> T. unpack name <> " tid=" <> show tid
53+ atomically $ getPutLock getLock key name)
54+ (\ l -> do
55+ atomically $ takeTMVar l
56+ liftIO $ do
57+ tid <- myThreadId
58+ traceIO $ " LOCK release " <> T. unpack name <> " tid=" <> show tid)
4959 (const a)
5060
5161withGetLocks :: MonadUnliftIO m => (k -> STM Lock ) -> Set k -> Text -> m a -> m a
5262withGetLocks getLock keys name = E. bracket holdLocks releaseLocks . const
5363 where
54- holdLocks = forConcurrently (S. toList keys) $ \ key -> atomically $ getPutLock getLock key name
55- releaseLocks = mapM_ (atomically . takeTMVar)
64+ holdLocks = do
65+ liftIO $ do
66+ tid <- myThreadId
67+ traceIO $ " LOCKS acquire " <> T. unpack name <> " (" <> show (S. size keys) <> " keys) tid=" <> show tid
68+ forConcurrently (S. toList keys) $ \ key -> atomically $ getPutLock getLock key name
69+ releaseLocks ls = do
70+ mapM_ (atomically . takeTMVar) ls
71+ liftIO $ do
72+ tid <- myThreadId
73+ traceIO $ " LOCKS release " <> T. unpack name <> " (" <> show (S. size keys) <> " keys) tid=" <> show tid
5674
5775-- getLock and putTMVar can be in one transaction on the assumption that getLock doesn't write in case the lock already exists,
5876-- and in case it is created and added to some shared resource (we use TMap) it also helps avoid contention for the newly created lock.
0 commit comments