haskell - 根据时间限制管道?

标签 haskell haskell-pipes

是否可以创建管道来获取在特定时间段内向下游发送的所有值?我正在实现一个服务器,该协议(protocol)允许我连接传出数据包并将它们压缩在一起,所以我想有效地“清空”下游队列ByteString每 100ms 和 mappend它们在一起,然后屈服于下一个进行压缩的管道。

最佳答案

这是使用 pipes-concurrency 的解决方案.你给它任何Input它会定期排出所有值的输入:

import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import Data.Foldable (forM_)
import Pipes
import Pipes.Concurrent

drainAll :: Input a -> STM (Maybe [a])
drainAll i = do
    ma <- recv i
    case ma of
        Nothing -> return Nothing
        Just a  -> loop (a:)
  where
    loop diffAs = do
        ma <- recv i <|> return Nothing
        case ma of
            Nothing -> return (Just (diffAs []))
            Just a  -> loop (diffAs . (a:))

bucketsEvery :: Int -> Input a -> Producer [a] IO ()
bucketsEvery microseconds i = loop
  where
    loop = do
        lift $ threadDelay microseconds
        ma <- lift $ atomically $ drainAll i
        forM_ ma $ \a -> do
            yield a
            loop

通过选择 Buffer 的类型,您可以更好地控制如何使用上游元素。您用来构建 Input .

如果您是 pipes-concurrency 的新手, 你可以阅读 the tutorial其中解释了如何使用 spawn , BufferInput .

关于haskell - 根据时间限制管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275802/

相关文章:

haskell - 如何将外部导出函数的参数传递到管道中?

haskell - 流媒体库中惯用的预取

haskell - 如何将状态与管道一起使用?

haskell - 如何将 IO 操作的输出传输到 haskell 中的进程中

http - 我怎么知道在我的 Haskell 程序中哪里可以抛出异常?

Haskell 元组连接函数定义问题

haskell - 无法通过 cabal 安装 sdl2

haskell - 打字判断有种类吗?

c - 从 Haskell 释放 C 运行时分配的内存

haskell - 表达式 `first @ (x:xs) ` 和 `second @(y:ys)` 是什么意思?