openlang

把函数转成深层处理器的续体

文档中深层处理器的例子有这么一段。

计算 f 本身也可以执行效果。当 f 执行 Yield 时,它的任务被暂停并放入就绪任务队列,然后调度器运行队列中的下一个任务。如果效果是 Fork f,就暂停当前任务,通过尾调用 spawn f 立即运行新任务 f。要注意,先运行新任务只是一个任意的选择。也可以把 f 的任务放进就绪队列,然后立即继续 k。

也许我漏掉了什么简单的东西,但看看这个调度器例子。

type _ Effect.t += Fork : (unit -> unit) -> unit t
                 | Yield : unit t

(* Round-robin scheduling with concurrency *)
let run (entry : unit -> unit) : unit =
  let pending : (int * (int, unit) continuation) option ref =
    ref None (* exchanger awaiting a partner *)
  in
  let ready = Queue.create () in (* ready-task queue *)
  let schedule cont arg =
    let resume () = continue cont arg in
    Queue.push
      resume ready
  in
  let next () =
    if Queue.is_empty ready then () (* finished *)
    else begin
      let resume = Queue.pop ready in
      resume ()
    end
  in
  let rec start (work : unit -> unit) : unit =
    match work () with
    | () -> next ()
    | exception err ->
        print_endline (Printexc.to_string err);
        next ()
    | effect Yield, cont -> schedule cont (); next ()
    (* How can work be queued at this point? *)
    | effect (Fork work), cont -> schedule cont (); start work
    | effect (Xchg value), cont ->
        begin match !pending with
        | Some (other, saved) -> pending := None; schedule saved value; continue cont other
        | None -> pending := Some (value, cont); next ()
        end
  in
  start entry

要怎样把 work 放进 ready?

从英语翻译查看原文

后续讨论 3

顺着彼此的依据读下去
  1. 固定链接

    我想可以跳过 schedule 这个辅助函数,直接操作 ready。

    不要写成

        | effect (Fork work), cont -> schedule cont (); start work

    而是交换顺序,写成这样。

        | effect (Fork work), cont -> Queue.push (fun () -> start work) ready; continue cont ()
    从英语翻译查看原文
  2. 固定链接

    不过这个版本似乎需要用 start 函数来包装,因为在处理器内部调用 work 时,它本身并没有被那个处理器包住。你觉得这是不可避免的吗,否则和例子里的调度器相比,结果似乎有点不对称?我只是想知道,为什么 Effect.Deep 没有一个类似 Effect.Shallow 的 fiber 的基本操作。

    从英语翻译查看原文

同一个问题的其他角度

  1. 请帮我看看 go 管道的实现(还在学习这门语言)

    大家好, 我正在学习 go 和它的并发功能,“管道”是常见模式之一。下面是我的实现,想请大家看看,并建议还有什么可以改进的地方 另外,还有哪些重要且常用的并发模式值得学习,比如 pubsub。 祝好, FV

    回复 3最近活动 go