Implement isEmptyMVar in terms of tryRead, not tryTake.

This commit is contained in:
Michael Walker 2017-04-07 22:55:54 +01:00
parent 5cd55a1921
commit d934222fe7
2 changed files with 13 additions and 5 deletions

View File

@ -10,6 +10,12 @@ This project is versioned according to the [Package Versioning Policy](https://p
unreleased 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 ### Miscellaneous
- There is now a changelog. - There is now a changelog.

View File

@ -50,6 +50,7 @@ module Control.Concurrent.Classy.MVar
import Control.Monad.Catch (mask_, onException) import Control.Monad.Catch (mask_, onException)
import Control.Monad.Conc.Class import Control.Monad.Conc.Class
import Data.Maybe (isJust)
-- | Swap the contents of a @MVar@, and return the value taken. This -- | Swap the contents of a @MVar@, and return the value taken. This
-- function is atomic only if there are no other producers fro 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. -- | 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 -- @since 1.0.0.0
isEmptyMVar :: MonadConc m => MVar m a -> m Bool isEmptyMVar :: MonadConc m => MVar m a -> m Bool
isEmptyMVar cvar = do isEmptyMVar = fmap isJust . tryReadMVar
val <- tryTakeMVar cvar
case val of
Just val' -> putMVar cvar val' >> pure True
Nothing -> pure False
-- | Operate on the contents of a @MVar@, replacing the contents after -- | Operate on the contents of a @MVar@, replacing the contents after
-- finishing. This operation is exception-safe: it will replace the -- finishing. This operation is exception-safe: it will replace the