PageRenderTime 35ms CodeModel.GetById 17ms app.highlight 12ms RepoModel.GetById 2ms app.codeStats 0ms

/server/thread_state.ml

http://github.com/hhughes/ocaml-frui
OCaml | 49 lines | 44 code | 5 blank | 0 comment | 31 complexity | 1b3c53a15394ea4f8b91ac65e98ea38a MD5 | raw file
 1let seed = 0
 2let _ = Random.init seed
 3let latest_tid = ref 0
 4let next_tid () = let tid = !latest_tid in latest_tid := tid+1; tid
 5
 6type thread_state = Started | Running | FunEnter | FunExit | Msg | Finished | Stop
 7
 8class thread =
 9object (self)
10  val tid = next_tid ()
11  val mutable in_fun = false
12  val mutable state = Started
13  val mutable fid = 0
14  method enterexit = if in_fun then FunExit else FunEnter
15  method stopexit = if in_fun then FunExit else Finished (* dont let us stop when in a function *)
16  method next_state p = function
17  | Started -> if p < 80 then Running else if p < 90 then self#enterexit else Msg
18  | Running -> if p < 40 then Running else if p < 60 then self#enterexit else if p < 90 then Msg else self#stopexit
19  | FunEnter -> if p < 50 then Running else if p < 70 then FunExit else Msg
20  | FunExit ->  if p < 40 then Running else if p < 50 then self#enterexit else if p < 80 then Msg else self#stopexit
21  | Msg -> if p < 60 then Running else if p < 80 then self#enterexit else if p < 90 then Msg else self#stopexit
22  | Finished -> Stop
23  | Stop -> Stop
24  method get_event a = function
25  | Started -> (Events.create tid fid Events.TStart) :: a
26  | Running -> a
27  | FunEnter -> in_fun <- true; (Events.create tid fid Events.FunStart) :: a
28  | FunExit -> let i = fid in fid <- i+1; in_fun <- false; (Events.create tid i Events.FunEnd) :: a
29  | Msg -> (Events.create tid fid Events.Msg) :: a
30  | Finished -> (Events.create tid fid Events.TEnd) :: a
31  | Stop -> a
32  method next_event a =
33    let e = self#get_event a state in
34    state <- self#next_state (Random.int 100) state;
35    e
36  method state = state
37end
38
39let threads = ref []
40
41let reset () =
42  threads := [];
43  latest_tid := 0
44
45let get_events () =
46  threads := List.filter (fun t -> t#state <> Stop) !threads;
47  if (Random.int 100) < 10 then threads := (new thread) :: !threads;
48  let events = List.fold_right (fun t -> t#next_event) !threads [] in
49  Json_io.string_of_json (Events.jsonify events)