Skip to content

Instantly share code, notes, and snippets.

@coot
Last active May 13, 2021 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coot/bbf2f8a2102fea466fdeba144ba1720b to your computer and use it in GitHub Desktop.
Save coot/bbf2f8a2102fea466fdeba144ba1720b to your computer and use it in GitHub Desktop.
LastToFinshSTM without `Semigroup` constraint.
module Synchronisation where
import Control.Concurrent
import Control.Concurrent.STM.TMVar
import Control.Monad.STM
newtype LastToFinishSTM a = LastToFinishSTM { runLastToFinish :: STM a }
instance Semigroup (LastToFinishSTM a) where
LastToFinishSTM ma <> LastToFinishSTM mb = LastToFinishSTM $ do
x <- (Left <$> ma) `orElse` (Right <$> mb)
case x of
Left _ -> mb
Right _ -> ma
-- returns 'True'
test :: IO Bool
test = do
a <- newEmptyTMVarIO
b <- newEmptyTMVarIO
forkIO $ do
threadDelay 250_000
atomically $ putTMVar a False
threadDelay 250_000
atomically $ putTMVar b True
atomically $ runLastToFinish $
LastToFinishSTM (readTMVar a) <> LastToFinishSTM (readTMVar b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment