Last active
May 13, 2021 21:06
-
-
Save coot/bbf2f8a2102fea466fdeba144ba1720b to your computer and use it in GitHub Desktop.
LastToFinshSTM without `Semigroup` constraint.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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