From d934222fe75af9154601bb581506b819e21f13ac Mon Sep 17 00:00:00 2001 From: Michael Walker Date: Fri, 7 Apr 2017 22:55:54 +0100 Subject: [PATCH] Implement isEmptyMVar in terms of tryRead, not tryTake. --- concurrency/CHANGELOG.markdown | 6 ++++++ concurrency/Control/Concurrent/Classy/MVar.hs | 12 +++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/concurrency/CHANGELOG.markdown b/concurrency/CHANGELOG.markdown index f838b42..3b92854 100644 --- a/concurrency/CHANGELOG.markdown +++ b/concurrency/CHANGELOG.markdown @@ -10,6 +10,12 @@ This project is versioned according to the [Package Versioning Policy](https://p unreleased ---------- +### Changed + +- The `isEmptyMVar` function is now implemented using `tryReadMVar` instead of a combination of + `tryTakeMVar` and `putMVar`. It no longer modifies the contents of the `MVar` and can no longer + block. + ### Miscellaneous - There is now a changelog. diff --git a/concurrency/Control/Concurrent/Classy/MVar.hs b/concurrency/Control/Concurrent/Classy/MVar.hs index c0eb799..96efc87 100644 --- a/concurrency/Control/Concurrent/Classy/MVar.hs +++ b/concurrency/Control/Concurrent/Classy/MVar.hs @@ -50,6 +50,7 @@ module Control.Concurrent.Classy.MVar import Control.Monad.Catch (mask_, onException) import Control.Monad.Conc.Class +import Data.Maybe (isJust) -- | Swap the contents of a @MVar@, and return the value taken. This -- function is atomic only if there are no other producers fro this @@ -64,13 +65,14 @@ swapMVar cvar a = mask_ $ do -- | Check if a @MVar@ is empty. -- +-- The boolean value returned is just a snapshot of the state of the +-- @MVar@, it may have been emptied (or filled) by the time you +-- actually access it. Generally prefer 'tryPutMVar', 'tryTakeMVar', +-- and 'tryReadMVar'. +-- -- @since 1.0.0.0 isEmptyMVar :: MonadConc m => MVar m a -> m Bool -isEmptyMVar cvar = do - val <- tryTakeMVar cvar - case val of - Just val' -> putMVar cvar val' >> pure True - Nothing -> pure False +isEmptyMVar = fmap isJust . tryReadMVar -- | Operate on the contents of a @MVar@, replacing the contents after -- finishing. This operation is exception-safe: it will replace the