异步映射中的同步部分 [英] Synchronized section in async map

查看:96
本文介绍了异步映射中的同步部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的IO函数,它将继续从文件夹加载数据,对数据执行纯计算,然后将其写回。



我正在运行此函数并行使用

  mapConcurrently_ iofun folderList 

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



这种方式完美无瑕,但有点太好了。现在,即使是 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

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?

解决方案

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

这篇关于异步映射中的同步部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆