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

标签 multithreading asynchronous ocaml ocaml-lwt mirage

我正在 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/

相关文章:

ocaml - OCaml 中的 "` 是什么?

ocaml - `Lazy.force` 和 `Lazy.force_val` 之间的区别

algorithm - List.mem 的复杂性

java - 在不同步的情况下通过 100 个不同的线程递增静态变量,但最终结果为 100

java - 如何使用 twitter4j 构建可靠的多线程 twitter api 查询应用程序?

java - 线程同步和单例问题

c# - ConfigureAwait(false) 和库代码中的事件

c++ - 正确使用 C++ STL 线程的仿函数

c++ - 使用 WxWidgets 异步执行

C#、Windows 服务和 Microsoft.Bcl.Async