我正在为一个类(class)项目开发一个小型反导弹模拟器。
想法是让不同的进程/线程相互通信。
我开始研究 Missile Laucher 应用程序。它的导弹必须是一根线。
所以这是我制作的开始代码:
open Missile;;
(* Name of the Station *)
let launcher_name = "Pacific";;
(* Gravitational Constant *)
let g = 9.8;;
(* Temporal Reference *)
let time = ref 0.0;;
(* Calculates the next position in time of the missile *)
let calculate_position () =
let nX = 10.0 *. !time and nY = (0.5) *. g**2.0 in (nX,nY);;
(* Launches the thread missile and updates its position *)
let launch mis =
while true do
let pos = mis#position () in
Printf.printf "%s\n" pos;
let (a,b) = calculate_position () in
mis#moveto (a,b);
time := !time +. 1.0;
(* Why isnt this working? *)
Thread.delay 0.25
done;;
(* test function *)
let launchMissile () =
Printf.printf "Launch Station %s launched a missile. \n" launcher_name;
let mis = new missile "Test" 1 "USA" in
let t1 = Thread.create launch mis in
Thread.join t1;;
launchMissile ();;
完成此操作后,我想通过随时间打印值来测试我的 CalculatePosition 函数。
但很明显,如果没有暂停或等待,它们打印出来的速度太快了。所以我考虑在每次 while 迭代中将线程延迟 0.25 秒。
我做错了什么?我尝试了很多不同的东西。只有 Thread.delay 函数表现得很奇怪。
我可以这样做吗?
如果您能提供帮助,那就太好了,我已经想不通了...并开始重新阅读我这里所有关于 Ocaml 的书籍。
如果对你来说分析问题也很重要,这里是我的导弹类:
class missile name id owner =
object
val mutable name = name;
val id = id;
val owner = owner;
val mutable x:float = 0.0
val mutable y:float = 0.0
method get_x = x
method get_y = y
method get_point = (x,y)
method moveto (a,b) = x <- a; y <- b
method rmoveto (dx, dy) = x <- x +. dx ; y <- y +. dy
method to_string () = "( " ^ "I am Missile " ^ (string_of_int id) ^ " and my owner is " ^ (owner) ^ ")";
method position () = "(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")";
method distance () = sqrt (x*.x +. y*.y)
end;;
谢谢
最佳答案
Printf.*
函数是缓冲的(我想是因为格式化功能),而 print_*
和 prerr_*
不是。如果将 printf
替换为 print_endline
,您将看到输出按预期发生,而无需 flush
缓冲区。
所以这与我最初所说的缓冲区争用或并发访问无关,而只是普通的内部(非系统)缓冲。
顺便说几句:你不需要在方法的末尾放分号(尽管语法接受它)。此外,表达式周围的括号在 ^
运算符之间是多余的。我想两者都是风格问题。
享受 OCaml!
关于multithreading - Ocaml : Thread. 延迟未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13781693/