【发布时间】:2010-09-19 11:22:17
【问题描述】:
我是 Haskell 初学者,我认为这是一个很好的练习。我有一个 我需要在线程A中读取文件的分配,处理文件行 在线程 B_i 中,然后在线程 C 中输出结果。
到目前为止,我已经实现了这一点,但其中一项要求是我们 不能相信整个文件都适合内存。我希望那个懒惰 IO 和垃圾收集器会为我执行此操作,但可惜内存使用情况 一直在上升。
阅读器线程 (A) 读取带有readFile 的文件,然后将其压缩
带有行号并用 Just 包裹。然后写入这些压缩线
到Control.Concurrent.Chan。每个消费者线程 B 都有自己的通道。
每个消费者在有数据时读取自己的频道,如果正则表达式 匹配,它被输出到各自的输出通道包装 在 Maybe 中(由列表组成)。
打印机检查每个 B 线程的输出通道。如果没有 结果(行)为Nothing,打印行。由于此时 不应该引用旧行,我认为垃圾 收集器将能够释放这些行,但唉,我似乎在 这里是错误的。
所以问题是,我如何限制内存使用,或者允许垃圾 收集器删除线条。
根据要求提供片段。希望缩进不会被严重破坏:)
data Global = Global {done :: MVar Bool, consumers :: Consumers}
type Done = Bool
type Linenum = Int
type Line = (Linenum, Maybe String)
type Output = MVar [Line]
type Input = Chan Line
type Consumers = MVar (M.Map ThreadId (Done, (Input, Output)))
type State a = ReaderT Global IO a
producer :: [Input] -> FilePath -> State ()
producer c p = do
liftIO $ Main.log "Starting producer"
d <- asks done
f <- liftIO $ readFile p
mapM_ (\l -> mapM_
(liftIO . flip writeChan l) c)
$ zip [1..] $ map Just $ lines f
liftIO $ modifyMVar_ d (return . not)
printer :: State ()
printer = do
liftIO $ Main.log "Starting printer"
c <- (fmap (map (snd . snd) . M.elems)
(asks consumers >>= liftIO . readMVar))
uniq' c
where head' :: Output -> IO Line
head' ch = fmap head (readMVar ch)
tail' = mapM_ (liftIO . flip modifyMVar_
(return . tail))
cont ch = tail' ch >> uniq' ch
printMsg ch = readMVar (head ch) >>=
liftIO . putStrLn . fromJust . snd . head
cempty :: [Output] -> IO Bool
cempty ch = fmap (any id)
(mapM (fmap ((==) 0 . length) . readMVar ) ch)
{- Return false unless none are Nothing -}
uniq :: [Output] -> IO Bool
uniq ch = fmap (any id . map (isNothing . snd))
(mapM (liftIO . head') ch)
uniq' :: [Output] -> State ()
uniq' ch = do
d <- consumersDone
e <- liftIO $ cempty ch
if not e
then do
u <- liftIO $ uniq ch
if u then cont ch else do
liftIO $ printMsg ch
cont ch
else unless d $ uniq' ch
【问题讨论】:
标签: haskell concurrency io heap-memory