Question

MonadResource is capable to track multiple resources. Sometimes deallocation order of these resources is important. Consider following code:

allocator1 = putStrLn "allocator1"
deallocator1 = putStrLn "deallocator1"

allocator2 = putStrLn "allocator2"
deallocator2 = putStrLn "deallocator2"

accessResource = const $ putStrLn "accessResource"

resourceTest :: MonadResource m => m ()
resourceTest = do
    (_, resource1) <- allocate allocator1 $ const deallocator1
    (_, resource2) <- allocate allocator2 $ const $ accessResource resource1 >> deallocator2
    return ()

main = runResourceT resourceTest 

Here I access resource1 from resource2 clean-up action, so I expect resource1 will always be deallocated after resource1, otherwise the code would be incorrect. And this is true at least in current implementation. If I run the code I will get:

allocator1
allocator2
accessResource
deallocator2
deallocator1

Does MonadResource always quarantine that resource allocated earlier (hence accessible from later clean-up actions) will be deallocated later, or deallocation order is implementation specific? If it implementation specific what is the best way to guarantee particular deallocation order?

Was it helpful?

Solution

Since version 0.3.2.1, deallocation is always in LIFO order. This was changed in respond to issue #46, which has more information. In other words, you can rely on deallocator2 always running before deallocator1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top