resource-simple-0.1: Allocate resources which are guaranteed to be released.

Safe HaskellSafe-Infered

Control.Monad.Resource

Contents

Description

Allocate resources which are guaranteed to be released.

One point to note: all register cleanup actions live in IO, not the main monad. This allows both more efficient code, and for monads to be transformed.

Synopsis

Data types

data ResourceT m a Source

The Resource transformer. This transformer keeps track of all registered actions, and calls them upon exit (via runResourceT). Actions may be registered via register, or resources may be allocated atomically via with. The with function corresponds closely to bracket.

Releasing may be performed before exit via the release function. This is a highly recommended optimization, as it will ensure that scarce resources are freed early. Note that calling release will deregister the action, so that a release action will only ever be called once.

data ReleaseKey Source

A lookup key for a specific release action. This value is returned by register and with and is passed to release.

Run

runResourceT :: MonadBaseControl IO m => ResourceT m a -> m aSource

Unwrap a ResourceT transformer, and call all registered release actions.

Note that there is some reference counting involved due to the MonadFork instance. If multiple threads are sharing the same collection of resources, only the last call to runResourceT will deallocate the resources.

Resource allocation

withSource

Arguments

:: MonadBase IO m 
=> IO a

allocate

-> (a -> IO ())

free resource

-> ResourceT m (ReleaseKey, a) 

Perform some allocation, and automatically register a cleanup action.

register :: MonadBase IO m => IO () -> ResourceT m ReleaseKeySource

Register some action that will be called precisely once, either when runResourceT is called, or when the ReleaseKey is passed to release.

release :: MonadBase IO m => ReleaseKey -> ResourceT m ()Source

Call a release action early, and deregister it from the list of cleanup actions to be performed.

Monad transformation

transResourceT :: (m a -> n b) -> ResourceT m a -> ResourceT n bSource

Transform the monad a ResourceT lives in. This is most often used to strip or add new transformers to a stack, e.g. to run a ReaderT.