module Ecluse.Runtime.Telemetry.Batched.Cells (
Cells,
newCells,
modifyOwnCell,
drainCells,
) where
import Data.Atomics (atomicModifyIORefCAS_)
import Data.Vector (Vector)
import Data.Vector qualified as V
import GHC.Conc (getNumCapabilities, myThreadId, threadCapability)
import GHC.IORef (atomicSwapIORef)
data Cells a = Cells
{ forall a. Cells a -> a
cellsBlank :: a
, forall a. Cells a -> IORef a
cellsFirst :: IORef a
, forall a. Cells a -> Vector (IORef a)
cellsAll :: Vector (IORef a)
}
newCells :: a -> IO (Cells a)
newCells :: forall a. a -> IO (Cells a)
newCells a
blank = do
count <- IO Int
getNumCapabilities
home <- newIORef blank
rest <- V.replicateM (count - 1) (newIORef blank)
pure Cells{cellsBlank = blank, cellsFirst = home, cellsAll = V.cons home rest}
modifyOwnCell :: Cells a -> (a -> a) -> IO ()
modifyOwnCell :: forall a. Cells a -> (a -> a) -> IO ()
modifyOwnCell Cells a
cells a -> a
change = do
(capability, _) <- ThreadId -> IO (Int, Bool)
threadCapability (ThreadId -> IO (Int, Bool)) -> IO ThreadId -> IO (Int, Bool)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IO ThreadId
myThreadId
atomicModifyIORefCAS_ (fromMaybe (cellsFirst cells) (cellsAll cells V.!? capability)) change
drainCells :: Cells a -> IO [a]
drainCells :: forall a. Cells a -> IO [a]
drainCells Cells a
cells = (IORef a -> IO a) -> [IORef a] -> IO [a]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (IORef a -> a -> IO a
forall a. IORef a -> a -> IO a
`atomicSwapIORef` Cells a -> a
forall a. Cells a -> a
cellsBlank Cells a
cells) (Vector (IORef a) -> [IORef a]
forall a. Vector a -> [a]
V.toList (Cells a -> Vector (IORef a)
forall a. Cells a -> Vector (IORef a)
cellsAll Cells a
cells))