    {-# LANGUAGE Trustworthy #-}
    {-# LANGUAGE NoImplicitPrelude, UnboxedTuples, MagicHash #-}

    -----------------------------------------------------------------------------
    -- |
    -- Module      :  Control.Concurrent.MVar
    -- Copyright   :  (c) The University of Glasgow 2001
    -- License     :  BSD-style (see the file libraries/base/LICENSE)
    --
    -- Maintainer  :  libraries@haskell.org
    -- Stability   :  stable
    -- Portability :  non-portable (concurrency)
    --
    -- An @'MVar' t@ is mutable location that is either empty or contains a
    -- value of type @t@.  It has two fundamental operations: 'putMVar'
    -- which fills an 'MVar' if it is empty and blocks otherwise, and
    -- 'takeMVar' which empties an 'MVar' if it is full and blocks
    -- otherwise.  They can be used in multiple different ways:
    --
    --   1. As synchronized mutable variables,
    --
    --   2. As channels, with 'takeMVar' and 'putMVar' as receive and send, and
    --
    --   3. As a binary semaphore @'MVar' ()@, with 'takeMVar' and 'putMVar' as
    --      wait and signal.
    --
    -- They were introduced in the paper
    -- <https://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz "Concurrent Haskell">
    -- by Simon Peyton Jones, Andrew Gordon and Sigbjorn Finne, though
    -- some details of their implementation have since then changed (in
    -- particular, a put on a full 'MVar' used to error, but now merely
    -- blocks.)
    --
    -- === Applicability
    --
    -- 'MVar's offer more flexibility than 'Data.IORef.IORef's, but less flexibility
    -- than 'GHC.Conc.STM'.  They are appropriate for building synchronization
    -- primitives and performing simple interthread communication; however
    -- they are very simple and susceptible to race conditions, deadlocks or
    -- uncaught exceptions.  Do not use them if you need perform larger
    -- atomic operations such as reading from multiple variables: use 'GHC.Conc.STM'
    -- instead.
    --
    -- In particular, the "bigger" functions in this module ('swapMVar',
    -- 'withMVar', 'modifyMVar_' and 'modifyMVar') are simply
    -- the composition of a 'takeMVar' followed by a 'putMVar' with
    -- exception safety.
    -- These have atomicity guarantees only if all other threads
    -- perform a 'takeMVar' before a 'putMVar' as well;  otherwise, they may
    -- block.
    --
    -- === Fairness
    --
    -- No thread can be blocked indefinitely on an 'MVar' unless another
    -- thread holds that 'MVar' indefinitely.  One usual implementation of
    -- this fairness guarantee is that threads blocked on an 'MVar' are
    -- served in a first-in-first-out fashion, but this is not guaranteed
    -- in the semantics.
    --
    -- === Gotchas
    --
    -- Like many other Haskell data structures, 'MVar's are lazy.  This
    -- means that if you place an expensive unevaluated thunk inside an
    -- 'MVar', it will be evaluated by the thread that consumes it, not the
    -- thread that produced it.  Be sure to 'evaluate' values to be placed
    -- in an 'MVar' to the appropriate normal form, or utilize a strict
    -- MVar provided by the strict-concurrency package.
    --
    -- === Ordering
    --
    -- 'MVar' operations are always observed to take place in the order
    -- they are written in the program, regardless of the memory model of
    -- the underlying machine.  This is in contrast to 'Data.IORef.IORef' operations
    -- which may appear out-of-order to another thread in some cases.
    --
    -- === Example
    --
    -- Consider the following concurrent data structure, a skip channel.
    -- This is a channel for an intermittent source of high bandwidth
    -- information (for example, mouse movement events.)  Writing to the
    -- channel never blocks, and reading from the channel only returns the
    -- most recent value, or blocks if there are no new values.  Multiple
    -- readers are supported with a @dupSkipChan@ operation.
    --
    -- A skip channel is a pair of 'MVar's. The first 'MVar' contains the
    -- current value, and a list of semaphores that need to be notified
    -- when it changes. The second 'MVar' is a semaphore for this particular
    -- reader: it is full if there is a value in the channel that this
    -- reader has not read yet, and empty otherwise.
    --
    -- @
    --     data SkipChan a = SkipChan (MVar (a, [MVar ()])) (MVar ())
    --
    --     newSkipChan :: IO (SkipChan a)
    --     newSkipChan = do
    --         sem <- newEmptyMVar
    --         main <- newMVar (undefined, [sem])
    --         return (SkipChan main sem)
    --
    --     putSkipChan :: SkipChan a -> a -> IO ()
    --     putSkipChan (SkipChan main _) v = do
    --         (_, sems) <- takeMVar main
    --         putMVar main (v, [])
    --         mapM_ (\sem -> putMVar sem ()) sems
    --
    --     getSkipChan :: SkipChan a -> IO a
    --     getSkipChan (SkipChan main sem) = do
    --         takeMVar sem
    --         (v, sems) <- takeMVar main
    --         putMVar main (v, sem:sems)
    --         return v
    --
    --     dupSkipChan :: SkipChan a -> IO (SkipChan a)
    --     dupSkipChan (SkipChan main _) = do
    --         sem <- newEmptyMVar
    --         (v, sems) <- takeMVar main
    --         putMVar main (v, sem:sems)
    --         return (SkipChan main sem)
    -- @
    --
    -- This example was adapted from the original Concurrent Haskell paper.
    -- For more examples of 'MVar's being used to build higher-level
    -- synchronization primitives, see 'Control.Concurrent.Chan' and
    -- 'Control.Concurrent.QSem'.
    --
    -----------------------------------------------------------------------------

    module Control.Concurrent.MVar
            (
              -- * @MVar@s
              MVar
            , newEmptyMVar
            , newMVar
            , takeMVar
            , putMVar
            , readMVar
            , swapMVar
            , tryTakeMVar
            , tryPutMVar
            , isEmptyMVar
            , withMVar
            , withMVarMasked
            , modifyMVar_
            , modifyMVar
            , modifyMVarMasked_
            , modifyMVarMasked
            , tryReadMVar
            , mkWeakMVar
            , addMVarFinalizer
        ) where

    import GHC.MVar ( MVar(..), newEmptyMVar, newMVar, takeMVar, putMVar,
                      tryTakeMVar, tryPutMVar, isEmptyMVar, readMVar,
                      tryReadMVar
                    )
    import qualified GHC.MVar
    import GHC.Weak
    import GHC.Base

    import Control.Exception.Base

    {-|
      Take a value from an 'MVar', put a new value into the 'MVar' and
      return the value taken. This function is atomic only if there are
      no other producers for this 'MVar'. In other words, it cannot guarantee
      that, by the time 'swapMVar' gets the chance to write to the MVar,
      the value of the MVar has not been altered
      by a write operation from another thread.
    -}
    swapMVar :: MVar a -> a -> IO a
    swapMVar :: forall a. MVar a -> a -> IO a
    swapMVar MVar a
    mvar a
    new =
      IO a -> IO a
    forall a. IO a -> IO a
    mask_ (IO a -> IO a) -> IO a -> IO a
    forall a b. (a -> b) -> a -> b
    $ do
        a
    old <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    mvar
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    mvar a
    new
        a -> IO a
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return a
    old

    {-|
      'withMVar' is an exception-safe wrapper for operating on the contents
      of an 'MVar'.  This operation is exception-safe: it will replace the
      original contents of the 'MVar' if an exception is raised (see
      "Control.Exception").  However, it is only atomic if there are no
      other producers for this 'MVar'. In other words, it cannot guarantee
      that, by the time 'withMVar' gets the chance to write to the MVar,
      the value of the MVar has not been altered
      by a write operation from another thread.
    -}
    {-# INLINE withMVar #-}
    -- inlining has been reported to have dramatic effects; see
    -- http://www.haskell.org//pipermail/haskell/2006-May/017907.html
    withMVar :: MVar a -> (a -> IO b) -> IO b
    withMVar :: forall a b. MVar a -> (a -> IO b) -> IO b
    withMVar MVar a
    m a -> IO b
    io =
      ((forall a. IO a -> IO a) -> IO b) -> IO b
    forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
    mask (((forall a. IO a -> IO a) -> IO b) -> IO b)
    -> ((forall a. IO a -> IO a) -> IO b) -> IO b
    forall a b. (a -> b) -> a -> b
    $ \forall a. IO a -> IO a
    restore -> do
        a
    a <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        b
    b <- IO b -> IO b
    forall a. IO a -> IO a
    restore (a -> IO b
    io a
    a) IO b -> IO () -> IO b
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        b -> IO b
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return b
    b

    {-|
      Like 'withMVar', but the @IO@ action in the second argument is executed
      with asynchronous exceptions masked.

      @since 4.7.0.0
    -}
    {-# INLINE withMVarMasked #-}
    withMVarMasked :: MVar a -> (a -> IO b) -> IO b
    withMVarMasked :: forall a b. MVar a -> (a -> IO b) -> IO b
    withMVarMasked MVar a
    m a -> IO b
    io =
      IO b -> IO b
    forall a. IO a -> IO a
    mask_ (IO b -> IO b) -> IO b -> IO b
    forall a b. (a -> b) -> a -> b
    $ do
        a
    a <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        b
    b <- a -> IO b
    io a
    a IO b -> IO () -> IO b
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        b -> IO b
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return b
    b

    {-|
      An exception-safe wrapper for modifying the contents of an 'MVar'.
      Like 'withMVar', 'modifyMVar' will replace the original contents of
      the 'MVar' if an exception is raised during the operation.  This
      function is only atomic if there are no other producers for this
      'MVar'. In other words, it cannot guarantee that, by the time
      'modifyMVar_' gets the chance to write to the MVar, the value
      of the MVar has not been altered by a write operation from another thread.
    -}
    {-# INLINE modifyMVar_ #-}
    modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
    modifyMVar_ :: forall a. MVar a -> (a -> IO a) -> IO ()
    modifyMVar_ MVar a
    m a -> IO a
    io =
      ((forall a. IO a -> IO a) -> IO ()) -> IO ()
    forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
    mask (((forall a. IO a -> IO a) -> IO ()) -> IO ())
    -> ((forall a. IO a -> IO a) -> IO ()) -> IO ()
    forall a b. (a -> b) -> a -> b
    $ \forall a. IO a -> IO a
    restore -> do
        a
    a  <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        a
    a' <- IO a -> IO a
    forall a. IO a -> IO a
    restore (a -> IO a
    io a
    a) IO a -> IO () -> IO a
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a'

    {-|
      A slight variation on 'modifyMVar_' that allows a value to be
      returned (@b@) in addition to the modified value of the 'MVar'.
    -}
    {-# INLINE modifyMVar #-}
    modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b
    modifyMVar :: forall a b. MVar a -> (a -> IO (a, b)) -> IO b
    modifyMVar MVar a
    m a -> IO (a, b)
    io =
      ((forall a. IO a -> IO a) -> IO b) -> IO b
    forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
    mask (((forall a. IO a -> IO a) -> IO b) -> IO b)
    -> ((forall a. IO a -> IO a) -> IO b) -> IO b
    forall a b. (a -> b) -> a -> b
    $ \forall a. IO a -> IO a
    restore -> do
        a
    a      <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        (a
    a',b
    b) <- IO (a, b) -> IO (a, b)
    forall a. IO a -> IO a
    restore (a -> IO (a, b)
    io a
    a IO (a, b) -> ((a, b) -> IO (a, b)) -> IO (a, b)
    forall a b. IO a -> (a -> IO b) -> IO b
    forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
    >>= (a, b) -> IO (a, b)
    forall a. a -> IO a
    evaluate) IO (a, b) -> IO () -> IO (a, b)
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a'
        b -> IO b
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return b
    b

    {-|
      Like 'modifyMVar_', but the @IO@ action in the second argument is executed with
      asynchronous exceptions masked.

      @since 4.6.0.0
    -}
    {-# INLINE modifyMVarMasked_ #-}
    modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO ()
    modifyMVarMasked_ :: forall a. MVar a -> (a -> IO a) -> IO ()
    modifyMVarMasked_ MVar a
    m a -> IO a
    io =
      IO () -> IO ()
    forall a. IO a -> IO a
    mask_ (IO () -> IO ()) -> IO () -> IO ()
    forall a b. (a -> b) -> a -> b
    $ do
        a
    a  <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        a
    a' <- a -> IO a
    io a
    a IO a -> IO () -> IO a
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a'

    {-|
      Like 'modifyMVar', but the @IO@ action in the second argument is executed with
      asynchronous exceptions masked.

      @since 4.6.0.0
    -}
    {-# INLINE modifyMVarMasked #-}
    modifyMVarMasked :: MVar a -> (a -> IO (a,b)) -> IO b
    modifyMVarMasked :: forall a b. MVar a -> (a -> IO (a, b)) -> IO b
    modifyMVarMasked MVar a
    m a -> IO (a, b)
    io =
      IO b -> IO b
    forall a. IO a -> IO a
    mask_ (IO b -> IO b) -> IO b -> IO b
    forall a b. (a -> b) -> a -> b
    $ do
        a
    a      <- MVar a -> IO a
    forall a. MVar a -> IO a
    takeMVar MVar a
    m
        (a
    a',b
    b) <- (a -> IO (a, b)
    io a
    a IO (a, b) -> ((a, b) -> IO (a, b)) -> IO (a, b)
    forall a b. IO a -> (a -> IO b) -> IO b
    forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
    >>= (a, b) -> IO (a, b)
    forall a. a -> IO a
    evaluate) IO (a, b) -> IO () -> IO (a, b)
    forall a b. IO a -> IO b -> IO a
    `onException` MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a
        MVar a -> a -> IO ()
    forall a. MVar a -> a -> IO ()
    putMVar MVar a
    m a
    a'
        b -> IO b
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return b
    b

    {-# DEPRECATED addMVarFinalizer "use 'mkWeakMVar' instead" #-} -- deprecated in 7.6
    addMVarFinalizer :: MVar a -> IO () -> IO ()
    addMVarFinalizer :: forall a. MVar a -> IO () -> IO ()
    addMVarFinalizer = MVar a -> IO () -> IO ()
    forall a. MVar a -> IO () -> IO ()
    GHC.MVar.addMVarFinalizer

    -- | Make a 'Weak' pointer to an 'MVar', using the second argument as
    -- a finalizer to run when 'MVar' is garbage-collected
    --
    -- @since 4.6.0.0
    mkWeakMVar :: MVar a -> IO () -> IO (Weak (MVar a))
    mkWeakMVar :: forall a. MVar a -> IO () -> IO (Weak (MVar a))
    mkWeakMVar m :: MVar a
    m@(MVar MVar# RealWorld a
    m#) (IO State# RealWorld -> (# State# RealWorld, () #)
    f) = (State# RealWorld -> (# State# RealWorld, Weak (MVar a) #))
    -> IO (Weak (MVar a))
    forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
    IO ((State# RealWorld -> (# State# RealWorld, Weak (MVar a) #))
     -> IO (Weak (MVar a)))
    -> (State# RealWorld -> (# State# RealWorld, Weak (MVar a) #))
    -> IO (Weak (MVar a))
    forall a b. (a -> b) -> a -> b
    $ \State# RealWorld
    s ->
        case MVar# RealWorld a
    -> MVar a
    -> (State# RealWorld -> (# State# RealWorld, () #))
    -> State# RealWorld
    -> (# State# RealWorld, Weak# (MVar a) #)
    forall a b c.
    a
    -> b
    -> (State# RealWorld -> (# State# RealWorld, c #))
    -> State# RealWorld
    -> (# State# RealWorld, Weak# b #)
    mkWeak# MVar# RealWorld a
    m# MVar a
    m State# RealWorld -> (# State# RealWorld, () #)
    f State# RealWorld
    s of (# State# RealWorld
    s1, Weak# (MVar a)
    w #) -> (# State# RealWorld
    s1, Weak# (MVar a) -> Weak (MVar a)
    forall v. Weak# v -> Weak v
    Weak Weak# (MVar a)
    w #)