Synchronized section in async map

2020-04-30 07:07发布

I have a big IO function that will continuesly load data from a folder, perform pure calculations on the data, and write it back.

I am running this function over multiple folders in parallel using

mapConcurrently_ iofun folderList

from http://hackage.haskell.org/package/async-2.1.1.1/docs/Control-Concurrent-Async.html#v%3amapConcurrently

This works perfecty... but a little bit too well. Now even the character output of the putStrLn calls are async, which leads to an unreadable console log.

Is there a way to make IO Actions synchronized or even better a synchronized version of putStrLn?

1条回答
beautiful°
2楼-- · 2020-04-30 07:34

The way you coordinate threads is via MVars or TVars if you want to use STM. You can read all about them in "Parallel and Concurrent Haskell". You could do something like:

do mutex <- newMVar ()
   let putStrLn' = withMVar mutex . const . putStrLn 
   mapConcurrently_ (iofunPrintingWith putStrLn') folderList
查看更多
登录 后发表回答