首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >取消一个Lwt。线程

取消一个Lwt。线程
EN

Stack Overflow用户
提问于 2015-12-28 08:31:56
回答 1查看 182关注 0票数 1

在我的一生中,我无法找到一种方法来处理lwt线程的取消。

这是我所拥有的,简约。

代码语言:javascript
复制
#require "lwt.unix, lwt.ppx"
open Lwt.Infix

let program =
  let counter = ref 1 in
  let can_cancel = fst (Lwt.task ()) in

  Lwt.async_exception_hook := (fun _ ->
    prerr_endline "some exception");

  Lwt.on_cancel can_cancel (fun () ->
            Lwt_io.printl "correct ending" |> Lwt.ignore_result);

  Lwt.async begin fun () ->
    let rec forever () =

      try%lwt
        Lwt_io.printl "Hello World" >>= fun () ->

        if !counter = 3 then Lwt.cancel can_cancel
        else counter := !counter + 1;
        Lwt_unix.sleep 0.5 >>= forever
      with
        Lwt.Canceled -> Lwt_io.printl "canceled inside function"
    in

    Lwt.catch forever begin function
      | Lwt.Canceled -> Lwt_io.printl "Cancled exception happened"
      | _ -> Lwt.return ()
    end
  end;
  can_cancel

let () =
  Lwt_main.run program

您可以看到我多次尝试捕获已取消的异常,但都没有效果。我的输出是

代码语言:javascript
复制
utop cancelable.ml                                                     ⏎
Hello World
Hello World
Hello World
correct ending
Exception: Lwt.Canceled.

在更宏伟的方案中,我有一个unit Lwt.t list ref,它是用Lwt.task创建的,然后我计划在列表中执行List.iter Lwt.cancel,然后用unit Lwt.t类型的新线程替换它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-28 08:43:22

我把尝试放在了错误的水平上。

这段代码显示了为Lwt.Canceled异常放置try/with的正确位置。

代码语言:javascript
复制
#require "lwt.unix, lwt.ppx"
open Lwt.Infix

let program =
  let counter = ref 1 in
  let can_cancel = fst (Lwt.task ()) in

  Lwt.async begin fun () ->
    let rec forever () =
        Lwt_io.printl "Hello World" >>= fun () ->
        if !counter = 3 then Lwt.cancel can_cancel
        else counter := !counter + 1;
        Lwt_unix.sleep 0.5 >>= forever
    in
    forever ()
  end;
  can_cancel

let () =
  try
    Lwt_main.run program
  with
    Lwt.Canceled -> Lwt_io.printl "ended" |> Lwt.ignore_result
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34490110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档