Skip to content

Instantly share code, notes, and snippets.

@koterpillar
Last active July 14, 2017 05:02
Show Gist options
  • Save koterpillar/844545a40ca1c74c506b064c01568076 to your computer and use it in GitHub Desktop.
Save koterpillar/844545a40ca1c74c506b064c01568076 to your computer and use it in GitHub Desktop.
import Control.Concurrent.STM
import qualified Data.Map as M
import Data.Maybe
main = do
pendingV <- atomically $ newTVar M.empty
let handleFst (key, ourVal) =
atomically $ do
pending <- readTVar pendingV
case M.lookup key pending of
Just (Right theirVal) -> return $ Just (ourVal, theirVal)
_ -> do
writeTVar pendingV $ M.insert key (Left ourVal) pending
return Nothing
let handleSnd (key, ourVal) =
atomically $ do
pending <- readTVar pendingV
case M.lookup key pending of
Just (Left theirVal) -> return $ Just (theirVal, ourVal)
_ -> do
writeTVar pendingV $ M.insert key (Right ourVal) pending
return Nothing
results <-
sequence
[ handleFst (1, "a1")
, handleSnd (2, True)
, handleSnd (1, False)
, handleFst (2, "a2")
]
print $ catMaybes results
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment