gpt4 book ai didi

multithreading - Lwt.async()不能按预期工作

转载 作者:行者123 更新时间:2023-12-03 12:59:43 26 4
gpt4 key购买 nike

我正在MirageOS(Unix)上用Ocaml开发一个Web服务,此刻我在Lwt.async()上遇到了一些麻烦。 Lwt文档指出以下内容:

val async : (unit -> 'a t) -> unit

async f starts a thread without waiting for the result. If it fails (now or later), the exception is given to Lwt.​async_exception_hook.

You should use this function if you want to start a thread that might fail and don't care what its return value is, nor when it terminates (for instance, because it is looping).



因此,我立即认为Lwt.async是运行某些测试并检查实际执行是否异步的理想选择。不幸的是,它没有按预期工作。我的代码如下:
let http_callback conn_id req _body =
Lwt.return(Uri.path (Cohttp.Request.uri req))
>>= function
| "/tester" -> Cohttp_lwt_body.to_string _body >>= fun res ->
log_lwt ~inject:(fun f -> f "Testing") >>= fun () ->
Lwt.async(fun () -> TEST.start 100 res !listOfIP);
H.respond_string ~status:`OK ~body:("DONE") ()
in
let spec = H.make ~callback:http_callback () in
CON.listen conduit (`TCP 8080) (H.listen spec)

为了清楚起见,TEST.start执行一系列线程化操作。考虑到任何返回/执行都应该被忽略,我假设Lwt.async中的函数做什么并不重要。我错了吗?

最后,我的问题是:为什么客户端实际上必须等待线程接收OK响应?带有或不带有异步的行为基本上是相同的。

最佳答案

如果异步线程阻塞了等待,则控制将仅切换回HTTP处理程序。如果在完成之前仅使用100%的CPU,则异步线程可能会先运行到完成。尝试在测试中休眠以进行检查。

关于multithreading - Lwt.async()不能按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979288/

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