问题描述
我有一个很大的IO函数,它将继续从文件夹加载数据,对数据执行纯计算,然后将其写回。
我正在运行此函数并行使用
mapConcurrently_ iofun folderList
from
这种方式完美无瑕,但有点太好了。现在,即使是 putStrLn
调用的字符输出也是异步的,这会导致无法读取的控制台日志。
有没有办法让IO操作同步,甚至更好的同步版本的putStrLn?
我有一个很大的IO函数,它将继续从文件夹加载数据,对数据执行纯计算,然后将其写回。
我正在运行此函数并行使用
mapConcurrently_ iofun folderList
from
这种方式完美无瑕,但有点太好了。现在,即使是 putStrLn
调用的字符输出也是异步的,这会导致无法读取的控制台日志。
有没有办法让IO操作同步,甚至更好的同步版本的putStrLn?
如果你想使用STM,你可以通过 MVar
s或 TVar
来协调线程。您可以在Parallel and Concurrent Haskell中阅读关于它们的所有信息。你可以这样做:
do互斥体< - newMVar()
let putStrLn'= withMVar互斥体。常量。 putStrLn
mapConcurrently_(iofunPrintingWith putStrLn')folderList
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
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?
The way you coordinate threads is via MVar
s or TVar
s 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
这篇关于异步映射中的同步部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!