hoare (empty) → 0.1.0.0
raw patch · 4 files changed
+316/−0 lines, 4 filesdep +asyncdep +basedep +deepseq
Dependencies added: async, base, deepseq, stm
Files
- hoare.cabal +60/−0
- lib/Control/Concurrent/Channel.hs +127/−0
- lib/Control/Concurrent/Channel/Endless.hs +63/−0
- lib/Control/Concurrent/TBCQueue.hs +66/−0
+ hoare.cabal view
@@ -0,0 +1,60 @@+cabal-version: 3.0+name: hoare+synopsis: Simple tools for communicating sequential processes+description:+ Hoare was right—many concurrent programs can be simply expressed+ as a series of concurrent actors (threads) consuming and producing+ messages. Haskell provides uniquely great tools (green threads and STM)+ for doing so. This package provides:++ - Functions for using bounded STM types like+ `TBQueue` and `TMVar` as /channels/ between threads.++ - A /closeable/ @TBCQueue@ for programs where the input ends.+version: 0.1.0.0+license: Zlib+author: Matt Kline+maintainer: matt@bitbashing.io+category: Concurrency+build-type: Simple+tested-with: GHC==9.8.4++source-repository head+ type: git+ location: https://github.com/mrkline/hoare++common shared+ ghc-options: -Weverything+ -Wno-all-missed-specialisations+ -Wno-implicit-prelude+ -Wno-missed-specialisations+ -Wno-missing-export-lists+ -Wno-missing-import-lists+ -Wno-missing-kind-signatures+ -Wno-missing-local-signatures+ -Wno-missing-role-annotations+ -Wno-missing-safe-haskell-mode+ -Wno-monomorphism-restriction+ -Wno-safe+ -Wno-type-defaults+ -Wno-unsafe+ -threaded+ -fno-ignore-asserts+ default-language: Haskell2010+ default-extensions: BangPatterns,+ DerivingStrategies,+ ImportQualifiedPost,+ LambdaCase,+ OverloadedRecordDot,+ RecordWildCards,++library+ import: shared+ exposed-modules: Control.Concurrent.Channel+ Control.Concurrent.Channel.Endless+ Control.Concurrent.TBCQueue+ hs-source-dirs: lib+ build-depends: base >=4.4 && < 5,+ async >= 2.2 && < 3,+ deepseq >= 1.5 && < 2,+ stm >= 2.5 && < 3,
+ lib/Control/Concurrent/Channel.hs view
@@ -0,0 +1,127 @@+-- | Tools for connecting communicating sequential processes (threads)+-- with closeable channels.+module Control.Concurrent.Channel(+ Channel (..),+ writeChannel',+ evalWriteChannel,+ evalWriteChannel',+ consumeChannel,+ stateConsumeChannel,+ feedChannel,+ evalFeedChannel,+ pipeline,+ pipeline_+) where++import Control.Concurrent.Async+import Control.Concurrent.STM+import Control.Concurrent.TBCQueue+import Control.Exception+import Control.DeepSeq+import Control.Monad++-- | Any closeable STM-based pipe for inter-thread communication.+class Channel c where+ -- | Returns @Just value@ until the channel is closed, blocking for the next value.+ readChannel :: c a -> STM (Maybe a)++ -- | Writes the given value to the channel if it's still open.+ --+ -- Returns whether the channel is still open so producers know when consumers no longer care.+ writeChannel :: c a -> a -> STM Bool++ -- | Closes the channel so that future writes are no-ops and readers get @Nothing@+ -- once all previously-written values are read.+ closeChannel :: c a -> STM ()++ isClosedChannel :: c a -> STM Bool++instance Channel TBCQueue where+ readChannel = readTBCQueue++ writeChannel = writeTBCQueue++ closeChannel = closeTBCQueue++ isClosedChannel = isClosedTBCQueue++-- More to follow? A TMVar-like closeable slot?++-- | Writes to the channel, asserting that it hasn't been closed.+--+-- Useful in situations where only the writer closes the channel.+writeChannel' :: (Channel c) => c a -> a -> STM ()+writeChannel' c v = do+ o <- writeChannel c v+ unless o $ error "absurd: writeChannel' on closed channel"++-- | Force a value to normal form before writing it to the given channel.+--+-- One of the goals of CSP is to divide work into independent tasks.+-- Forcing values before passing them to the next actor can improve performance—it+-- keeps the last one in the chain from doing more than its share of evaluation.+evalWriteChannel :: (Channel c, NFData a) => c a -> a -> IO Bool+evalWriteChannel c v = do+ v' <- evaluate $ force v+ atomically $ writeChannel c v'++-- | `writeChannel'` meets `evalWriteChannel`+evalWriteChannel' :: (Channel c, NFData a) => c a -> a -> IO ()+evalWriteChannel' c v = do+ v' <- evaluate $ force v+ atomically $ writeChannel' c v'++-- | Consume the given channel until it closes,+-- passing values to the given action and collecting its results.+consumeChannel :: (Channel c, Monoid m) => c a -> (a -> IO m) -> IO m+consumeChannel c f = atomically (readChannel c) >>= \case+ Just v -> do+ res <- f v+ mappend res <$!> consumeChannel c f+ Nothing -> pure mempty++-- | Consume the given channel until it closes,+-- with each action updating some state. Returns the final state.+stateConsumeChannel :: (Channel c) => c a -> s -> (s -> a -> IO s) -> IO s+stateConsumeChannel c !state f = atomically (readChannel c) >>= \case+ Just v -> do+ next <- f state v+ stateConsumeChannel c next f+ Nothing -> pure state++feedChannel' :: (Channel c) => c a -> IO (Maybe a) -> IO ()+feedChannel' c f = f >>= \case+ Just v -> do+ stillOpen <- atomically $ writeChannel c v+ when stillOpen $ feedChannel' c f+ Nothing -> atomically $ closeChannel c++-- | Produce values with the given IO action,+-- feeding them into the given channel until it closes or the action returns @Nothing@.+feedChannel :: (Channel c) => c a -> IO (Maybe a) -> IO ()+feedChannel c f = do+ -- Protect against an f that could block for a long time (e.g., a network socket),+ -- even after the consumer hangs up.+ let chanClosed = atomically $ isClosedChannel c >>= check+ race_ (feedChannel' c f) chanClosed++-- | `feedChannel`, but forces produced values.+--+-- See `evalWriteChannel` for the motivation.+evalFeedChannel :: (Channel c, NFData a) => c a -> IO (Maybe a) -> IO ()+evalFeedChannel c f = feedChannel c f' where+ f' = f >>= evaluate . force+{-# INLINE evalFeedChannel #-}++-- | Create a channel with the given action,+-- then wire it to the given producer and consumer.+pipeline :: (Channel c) => IO (c a) -> (c a -> IO x) -> (c a -> IO y) -> IO (x, y)+pipeline new producer consumer = do+ c <- new+ let producer' = producer c `finally` atomically (closeChannel c)+ concurrently producer' (consumer c)++-- | `pipeline`, but ignore the results.+pipeline_ :: (Channel c) => IO (c a) -> (c a -> IO x) -> (c a -> IO y) -> IO ()+pipeline_ n p c = void $ pipeline n p c+{-# INLINE pipeline_ #-}
+ lib/Control/Concurrent/Channel/Endless.hs view
@@ -0,0 +1,63 @@+-- | Tools for connecting communicating sequential processes (threads)+-- with endless channels.+--+-- Many useful programs have no end to their input—they run in a steady state until killed.+-- This module provides the same utilities as "Control.Concurrent.Channel" (see those docs),+-- but for standard STM types we know and love.+module Control.Concurrent.Channel.Endless(+ Channel (..),+ evalWriteChannel,+ consumeChannel,+ feedChannel,+ evalFeedChannel,+ pipeline,+ pipeline_+) where++import Control.Concurrent.Async+import Control.Concurrent.STM+import Control.Exception+import Control.DeepSeq+import Control.Monad++class Channel c where+ readChannel :: c a -> STM a++ writeChannel :: c a -> a -> STM ()++instance Channel TBQueue where+ readChannel = readTBQueue++ writeChannel = writeTBQueue++instance Channel TMVar where+ readChannel = takeTMVar++ writeChannel = writeTMVar++evalWriteChannel :: (Channel c, NFData a) => c a -> a -> IO ()+evalWriteChannel c v = do+ v' <- evaluate $ force v+ atomically $ writeChannel c v'++consumeChannel :: (Channel c) => c a -> (a -> IO ()) -> IO ()+consumeChannel c f = forever $ atomically (readChannel c) >>= f++feedChannel :: (Channel c) => c a -> IO a -> IO ()+feedChannel c f = forever $ f >>= atomically . writeChannel c++evalFeedChannel :: (Channel c, NFData a) => c a -> IO a -> IO ()+evalFeedChannel c f = feedChannel c f' where+ f' = f >>= evaluate . force+{-# INLINE evalFeedChannel #-}++-- There's not much to these when you don't ever close, but for completeness:++pipeline :: IO c -> (c -> IO x) -> (c -> IO y) -> IO (x, y)+pipeline new producer consumer = do+ c <- new+ concurrently (producer c) (consumer c)++pipeline_ :: IO c -> (c -> IO x) -> (c -> IO y) -> IO ()+pipeline_ n p c = void $ pipeline n p c+{-# INLINE pipeline_ #-}
+ lib/Control/Concurrent/TBCQueue.hs view
@@ -0,0 +1,66 @@+-- | A /closeable/, bounded STM queue.+module Control.Concurrent.TBCQueue(+ TBCQueue,+ newTBCQueue,+ newTBCQueueIO,+ readTBCQueue,+ writeTBCQueue,+ closeTBCQueue,+ isOpenTBCQueue,+ isClosedTBCQueue,+ lengthTBCQueue+) where++import Control.Concurrent.STM+import Control.Monad+import Numeric.Natural++data TBCQueue a = TBCQueue {+ q :: !(TBQueue a),+ open :: !(TVar Bool)+}++newTBCQueue :: Natural -> STM (TBCQueue a)+newTBCQueue n = TBCQueue <$> newTBQueue n <*> newTVar True++-- | @atomically . newTBCQueue@+newTBCQueueIO :: Natural -> IO (TBCQueue a)+newTBCQueueIO = atomically . newTBCQueue++-- | Returns @Just value@ until the queue is closed, blocking for the next value.+readTBCQueue :: TBCQueue a -> STM (Maybe a)+readTBCQueue c = do+ mv <- tryReadTBQueue c.q+ case mv of+ Just v -> pure $ Just v+ Nothing -> do+ stillOpen <- readTVar c.open+ if stillOpen+ then retry+ else pure Nothing++-- | Writes the given value to the queue if it's still open.+--+-- Returns whether the queue is still open so producers know when consumers no longer care.+writeTBCQueue :: TBCQueue a -> a -> STM Bool+writeTBCQueue c !v = do+ stillOpen <- readTVar c.open+ when stillOpen $ writeTBQueue c.q v+ pure stillOpen++-- | Closes the queue so that future writes are no-ops and readers get @Nothing@+-- once all previously-written values are read.+closeTBCQueue :: TBCQueue a -> STM ()+closeTBCQueue c = writeTVar c.open False++isOpenTBCQueue :: TBCQueue a -> STM Bool+isOpenTBCQueue c = readTVar c.open++isClosedTBCQueue :: TBCQueue a -> STM Bool+isClosedTBCQueue = fmap not . isOpenTBCQueue++-- | The number of items currently in the queue.+--+-- It is obviously racy to use this value outside the current STM transaction.+lengthTBCQueue :: TBCQueue a -> STM Natural+lengthTBCQueue c = lengthTBQueue c.q