Created
April 3, 2021 20:01
-
-
Save aljce/24601f4a28254747ce2ff94b4861d98f to your computer and use it in GitHub Desktop.
This file contains 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
import Control.Exception (finally) | |
import Control.Concurrent.STM (atomically) | |
import Control.Concurrent.STM.TMVar (TMVar, newEmptyTMVarIO, takeTMVar, putTMVar, readTMVar) | |
prerun :: (IO a -> IO (IO b)) -> IO (IO a -> IO b) | |
prerun f = do | |
mailbox <- newEmptyTMVarIO | |
-- mailbox for actions (IO a) | |
mb <- f (join (atomically (readTMVar mailbox))) | |
-- run the action inside the mailbox up to n times | |
pure $ | |
\ma -> do | |
atomically (putTMVar mailbox ma) | |
-- fill mailbox with a specific action | |
-- this will block if other threads attempt to run f | |
mb `finally` atomically (takeTMVar mailbox) | |
-- empty the mailbox so other threads can run f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment