Synchronized section in async map

▼魔方 西西 提交于 2019-12-04 05:09:36

问题


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:


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


来源:https://stackoverflow.com/questions/44916052/synchronized-section-in-async-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!