Skip to content

Instantly share code, notes, and snippets.

@aljce
Created April 3, 2021 20:01
Show Gist options
  • Save aljce/24601f4a28254747ce2ff94b4861d98f to your computer and use it in GitHub Desktop.
Save aljce/24601f4a28254747ce2ff94b4861d98f to your computer and use it in GitHub Desktop.
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