OCaml事件/通道教程?

7
我正在使用OCaml。
我想模拟通信节点,以研究在不同通信方案下消息传播的速度等情况。
这些节点可以1.发送和2.接收固定消息。我认为显而易见的做法是将每个节点作为单独的线程。
显然,你可以使用Event模块和channels让线程彼此传递信息,但我找不到任何相关示例。有人能指点一下我或者给我一个简单的相关示例吗?
非常感谢。
3个回答

8

是的,您可以使用OCaml的Event模块。您可以在在线O'Reilly书籍中找到其使用示例。


如何尝试从多个通道读取数据? - David 天宇 Wong

6
如果您要尝试模拟,那么您需要比仅使用线程更多地控制节点,否则将会非常困难。
对于这个话题,我的主观做法是创建一个简单的单线程虚拟机,以便完全控制模拟。在OCaml中最简单的方法是使用类似单子的结构(例如在Lwt中使用的方式):
(* A thread is a piece of code that can be executed to perform some
   side-effects and fork zero, one or more threads before returning. 
   Some threads may block when waiting for an event to happen. *)
type thread = < run : thread list ; block : bool >

(* References can be used as communication channels out-of-the box (simply 
   read and write values ot them). To implement a blocking communication 
   pattern, use these two primitives: *)

let write r x next = object (self) 
  method block = !r <> None
  method run   = if self # block then [self]
                 else r := Some x ; [next ()]
end

let read r next = object (self) 
  method block = !r = None
  method run   = match r with 
                  | None -> [self]
                  | Some x -> r := None ; [next x]
end

您可以创建适合自己需求的更好的基元,例如在通道中添加“传输所需时间”属性。

下一步是定义模拟引擎。

(* The simulation engine can be implemented as a simple queue. It starts 
   with a pre-defined set of threads and returns when no threads are left, 
   or when all threads are blocking. *)
let simulate threads = 
  let q = Queue.create () in 
  let () = List.iter (fun t -> Queue.push t q) threads in 
  let rec loop blocking = 
    if Queue.is_empty q then `AllThreadsTerminated else 
      if Queue.length q = blocking then `AllThreadsBlocked else 
        let thread = Queue.pop q in 
        if thread # block then ( 
          Queue.push thread q ; 
          loop (blocking + 1) 
        ) else ( 
          List.iter (fun t -> Queue.push t q) (thread # run) ; 
          loop 0
        ) 
  in
  loop 0 

再次强调,您可以调整引擎以跟踪执行哪个线程的节点,以保持每个节点的优先级,以模拟一个节点比其他节点慢得多或快得多,或在每个步骤中随机选择要执行的线程等等。

最后一步是执行模拟。在这里,我将有两个线程来回发送随机数。

let rec thread name input output = 
  write output (Random.int 1024) (fun () -> 
    read input (fun value ->
      Printf.printf "%s : %d" name value ; 
      print_newline () ;
      thread name input output
  ))

let a = ref None and b = ref None 
let _ = simulate [ thread "A -> B" a b ; thread "B -> A" b a ]        

那是一个非常棒的答案,非常鼓舞人心。 - Tiemen

5

看起来你在想John Reppy的Concurrent ML。OCaml似乎有类似的东西,这里有介绍。

@Thomas给出的答案也很有价值,但如果你想使用这种并发编程风格,我建议阅读John Reppy的博士论文,它非常易读,并清晰地阐述了CML背后的动机以及一些重要的使用示例。如果你对语义不感兴趣,可以跳过该部分而仍然能够阅读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接