Monad multithreading

I need to start several simultaneous processes in the context of the same monad, say Connection . I was expecting something like the following to work:

 main = runConnection connectionSettings $ do forkIO action1 forkIO action2 action3 

but forkIO needs to be run in the context of IO and the actions that should be in IO too.

Assuming these actions are of type :: Connection () , what needs to be done to run them simultaneously (which instances to implement, etc.)?

I am currently working on this as follows, but obviously this is wrong:

 main = do forkIO $ runConnection connectionSettings action1 forkIO $ runConnection connectionSettings action2 runConnection connectionSettings action3 
+4
source share
1 answer

I found a beautiful library "monad-parallel" , designed for very similar purposes, and its even more powerful fork - "classy-parallel" .

In order for the monad to be used with the possibility of parallelism, it must have an instance of Parallel typeclass. And the classy-parallel library already provides instances for the most important types for such purposes: ResourceT IO and ReaderT .

Assuming you have the appropriate instances, the code in question can be converted to the following:

 import qualified Control.Monad.Parallel as Parallel main = runConnection connectionSettings $ Parallel.sequence [action1, action2, action3] 

For simple formatting, ResourceT may be useful resourceForkIO . There is also a monad-fork library that provides a neat and simple generalization over forking over forkIO and resourceForkIO .

+3
source

All Articles