gpt4 book ai didi

multithreading - F# MailboxProcessor 问题

转载 作者:行者123 更新时间:2023-12-04 06:52:08 25 4
gpt4 key购买 nike

我使用 http://fssnip.net/3K 中的代码创建了一个控制台程序.我发现

  1. 我想在末尾添加“System.Console.ReadLine() |> ignore”以等待线程完成。是否可以告诉所有 MailBoxProcessor 都已完成并且程序可以自行退出?

  2. 我尝试将测试 url“www.google.com”更改为无效的 url,但得到了以下输出。能否避免“输出竞赛”?

     http://www.google.co1m crawled by agent 1.       AgAAAent gent 3 is done.       gent 2 is done.       5 is done.       gent 4 is done.       Agent USupervisor RL collector is done.       is done.       1 is done.

[Edit]

The last output/crawling is still terminated after using Tomas's update http://fssnip.net/65. The following is the output of the program after I changed the "limit" to 5 and added some debugging messages. The last line shows the truncated URL. Is it a way to detect if all the crawlers finish their execution?

[Main] before crawl
[Crawl] before return result
http://news.google.com crawled by agent 1.
[supervisor] reached limit
http://www.gstatic.com/news/img/favicon.ico crawled by agent 5.
Agent 2 is done.
[supervisor] reached limit
Agent 5 is done.
http://www.google.com/imghp?hl=en&tab=ni crawled by agent 3.
[supervisor] reached limit
Agent 3 is done.
http://www.google.com/webhp?hl=en&tab=nw crawled by agent 4.
[supervisor] reached limit
Agent 4 is done.
http://news.google.com/n

我把主要代码改成了

printfn "[Main] before crawl"
crawl "http://news.google.com" 5
|> Async.RunSynchronously
printfn "[Main] after crawl"

但是,最后一个 printfn "[Main] after crawl" 永远不会执行,除非我在末尾添加一个 Console.Readline()。

[编辑2]

代码在 fsi 下运行良好。但是,如果使用它运行,它将遇到相同的问题 fsi --use:Program.fs --exec --quiet

最佳答案

我创建了一个片段,它使用您询问的两个功能扩展了前一个片段:http://fssnip.net/65 .

  1. 为了解决这个问题,我添加了 Start携带 AsyncReplyChannel<unit> 的消息.当主管代理启动时,它等待这个消息并保存回复 channel 以备后用。完成后,它会使用此 channel 发送回复。

    启动代理的函数返回等待回复的异步工作流。然后您可以调用 crawl使用 Async.RunSynchronously ,它将在主管代理完成时完成。

  2. 为避免打印时出现竞争,您需要同步所有打印件。最简单的方法是编写一个新代理 :-)。代理接收字符串并将它们一个一个地打印到输出(这样它们就不能交错)。该代码段隐藏了标准 printfn具有将字符串发送到代理的新实现的函数。

关于multithreading - F# MailboxProcessor 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com