我想我们如何用像 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/