Skip to content

Instantly share code, notes, and snippets.

@Lucus16
Created July 7, 2023 12:51
Show Gist options
  • Select an option

  • Save Lucus16/6592b54ab8c2e6f68f60be7d95c8cab3 to your computer and use it in GitHub Desktop.

Select an option

Save Lucus16/6592b54ab8c2e6f68f60be7d95c8cab3 to your computer and use it in GitHub Desktop.
newtype Pool r = Pool (TVar (Seq r))
newPool :: [r] -> IO (Pool r)
newPool = fmap Pool . newTVarIO . Seq.fromList
getResource :: Pool r -> IO r
getResource (Pool pool) = STM.atomically do
rs <- STM.readTVar pool
case rs of
Seq.Empty -> STM.retry
r :<| rs' -> writeTVar pool rs' $> r
putResource :: Pool r -> r -> IO ()
putResource (Pool pool) r = STM.atomically $ STM.modifyTVar' pool (:|> r)
-- Will block until resource is available
withResource :: Pool r -> (r -> IO a) -> IO a
withResource pool = bracket (getResource pool) (putResource pool)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment