如果您要尝试模拟,那么您需要对节点进行更多的控制,而不是仅仅使用线程所允许的——或者至少,没有大的痛苦。
我对此主题的主观方法是创建一个简单的单线程虚拟机,以保持对模拟的完全控制。在 OCaml 中这样做最简单的方法是使用类似 monad 的结构(例如在 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 ]