【问题标题】:Synchronized section in async map异步映射中的同步部分
【发布时间】:2017-07-05 02:11:29
【问题描述】:

我有一个大 IO 函数,它会不断地从文件夹中加载数据,对数据执行纯计算,然后将其写回。

我正在使用多个文件夹并行运行此功能

mapConcurrently_ iofun folderList

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

这很好用......但有点太好了。现在,即使putStrLn 调用的字符输出也是异步的,这会导致控制台日志无法读取。

有没有办法使 IO Actions 同步,甚至是 putStrLn 的同步版本更好?

【问题讨论】:

    标签: haskell asynchronous synchronized


    【解决方案1】:

    如果你想使用 STM,你协调线程的方式是通过MVars 或TVars。您可以在“Parallel and Concurrent Haskell”中阅读所有关于它们的信息。你可以这样做:

    do mutex <- newMVar ()
       let putStrLn' = withMVar mutex . const . putStrLn 
       mapConcurrently_ (iofunPrintingWith putStrLn') folderList
    

    【讨论】:

    • 阅读async的源码你也可以学到很多东西。这是一个非常简单的库,这要归功于 stm 原语的强大功能
    猜你喜欢
    • 2020-12-24
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2022-10-15
    相关资源
    最近更新 更多