multithreading - Haskell 中的生产者和消费者问题?

标签 multithreading haskell concurrency functional-programming

我想我们如何用像 Haskell 这样的函数式编程语言来实现生产者/消费者?以及它与命令式语言有何不同?我对函数式编程语言的理解是原始的。任何帮助将不胜感激。

最佳答案

使用通过 channel 传递的抢占线程和消息的生产者/消费者抽象:

import Data.Char
import Control.Concurrent
import Control.Concurrent.Chan

main = do
    c  <- newChan
    cs <- getChanContents c     -- a lazy stream of events from eventReader
    forkIO (producer c)          -- char producer
    consumer cs

  where
    -- thread one: the event producer
    producer c = forever $ do
        key <- getChar
        writeChan c key

    -- thread two: the lazy consumer
    consumer = mapM_ print . map shift
        where shift c | isAlpha c = chr (ord c + 1)
                           | otherwise = c

您将在 Erlang 中使用类似的模型。代表消费者和生产者的线程,以及它们之间的共享消息管道,每个都异步执行。

关于multithreading - Haskell 中的生产者和消费者问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1268307/

相关文章:

ios - Swift CoreData : error: Serious application error. 在核心数据更改处理期间捕获到异常。

haskell - Yesod 的 TH 生成了错误的代码?

haskell - 为什么 5::Sum Integer 与字面量一样工作?

haskell - 在 Haskell 中使用 'Either'

go - 这对并发访问是线程安全的吗?

java - 如何测试接受命令行参数的并发 Java 程序?

java - 实践中的并发循环缓冲区错误?

python-3.x - 多线程 celery worker 的任务划分

用于读取大量文件的 C# 守护进程

c++ - 队列和线程池之间的交互?