----------------------------------------------------------------------------
-- |
-- Module      :  DAP.Internal
-- Copyright   :  (C) 2023 David M. Johnson
-- License     :  BSD3-style (see the file LICENSE)
-- Stability   :  experimental
-- Portability :  non-portable
-- Description :  Internal functions for consumption by other modules like Server.hs
----------------------------------------------------------------------------
module DAP.Internal
  ( withLock
  , withGlobalLock
  ) where
----------------------------------------------------------------------------
import           Control.Concurrent         ( modifyMVar_, newMVar, MVar )
import           System.IO.Unsafe           ( unsafePerformIO )
----------------------------------------------------------------------------
-- | Used for logging in the presence of multiple threads.
lock :: MVar ()
{-# NOINLINE lock #-}
lock :: MVar ()
lock = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ forall a. a -> IO (MVar a)
newMVar ()
----------------------------------------------------------------------------
-- | Used for performing actions (e.g. printing debug logs to stdout)
-- Also used for writing to each connections Handle.
-- Ensures operations occur one thread at a time.
--
-- Used internally only
--
withLock :: MVar () -> IO () -> IO ()
withLock :: MVar () -> IO () -> IO ()
withLock MVar ()
mvar IO ()
action = forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ MVar ()
mvar forall a b. (a -> b) -> a -> b
$ \()
x -> ()
x forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ IO ()
action
----------------------------------------------------------------------------
-- | Used for performing actions (e.g. printing debug logs to stdout)
-- Ensures operations occur one thread at a time.
--
-- Used internally only
--
withGlobalLock :: IO () -> IO ()
withGlobalLock :: IO () -> IO ()
withGlobalLock = MVar () -> IO () -> IO ()
withLock MVar ()
lock
----------------------------------------------------------------------------