我试图创建一个计算斐波那契数的线程。效果很好,但是后来我尝试创建另一个线程,如果要花费x秒钟以上的时间来计算,它将停止计算线程。
这是我的代码:
module TimedFuture : sig
type 'a t
val create : ('a -> 'b) -> 'a -> float -> 'b t
val get : 'a t -> 'a option
end = struct
type 'a t = 'a Event.channel
let create f a t =
let c = Event.new_channel () in
let rec loop f = f (); loop f in
let task () =
let b = f a in
loop (fun () -> Event.(sync (send c b)))
in
let start_calc_thread () =
let t1 = Thread.create task () in
while ((Unix.gettimeofday () -. t) < 1.0) do
Printf.printf "Thread should keep running: %f\n"
(Unix.gettimeofday () -. t);
done;
try Thread.kill t1 with t1 -> ();
Printf.printf "Thread stoped\n"
in
let _ = Thread.create start_calc_thread () in
c
let get c = Some Event.(sync (receive c))
end
let option_to_i o = match o with
| None -> 0
| Some x -> x
let test =
let rec f x = match x with
| 1 -> 1
| 2 -> 1
| _ -> f (x-1) + f (x-2)
in
let t = Unix.gettimeofday () in
let ff = TimedFuture.create f 40 t in
Printf.printf "\nResult: %i\n" (option_to_i (TimedFuture.get ff)),
ff
当我编译代码并运行它时,尽管我在终端中看到了“线程停止”,但计算线程并没有停止工作。
你看到我的错了吗?
最佳答案
线程只能在特定的取消点被中断,特别是在用户代码将控制权交还给运行时的点上,以便后者可以执行其工作。一个特定的取消点是分配。由于您的代码未分配,并且合理实现的斐波那契也不会分配,因此无法停止它。如果您的实际算法确实没有取消点,那么您应该显式添加它们或使用过程。要添加明确的取消点,只需添加Thread.yield
即可。
关于multithreading - 线程计算OCaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113256/