Is the Haskell STM `check` different from the explicit use of` retry`?

I am experimenting with STM, implementing messes philsophers problems.

Anyway, I have the following definitions.

data ChopStick = CS (TVar Bool)

takeChopstick :: ChopStick -> STM ()
takeChopstick (CS chopstick) = do
    isTaken <- readTVar chopstick
    check (isTaken)
    writeTVar chopstick True

      

This function is called atomically:

atomically $ do
    takeChopstick leftChopstick
    takeChopstick rightChopstick

      

When I run the program with the above definition of takeChopstick, I get different results for running this definition:

takeChopstick :: ChopStick -> STM ()
takeChopstick (CS chopstick) = do
    isTaken <- readTVar chopstick
    if isTaken
        then retry
        else writeTVar chopstick True

      

In particular, the program freezes.

The source code for check

(hackage, stm-2.2.0.1) looks like this:

check :: Bool -> STM a
check b = if b then return undefined else retry

      

It looks like this is indeed the same as explicit usage retry

.

How check

is it different from explicit use retry

? Is retry

pushing the call further, forcing it to restart another atomic block?

+3


source to share


1 answer


No, check

no different from using retry

explicitly, I'm just confusing the argument check

.

The decision matters check

what isTaken

is False

, i.e. check $ not isTaken

...



takeChopstick :: ChopStick -> STM ()
takeChopstick (CS chopstick) = do
    isTaken <- readTVar chopstick
    check (not isTaken)
    writeTVar chopstick True

      

+3


source







All Articles