File: token2.ml

package info (click to toggle)
ocaml 4.02.3-9
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,076 kB
  • ctags: 30,429
  • sloc: ml: 154,213; ansic: 38,324; sh: 5,236; makefile: 4,569; asm: 4,283; lisp: 4,224; awk: 88; perl: 87; fortran: 21; cs: 9; sed: 9
file content (51 lines) | stat: -rw-r--r-- 1,965 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(***********************************************************************)
(*                                                                     *)
(*                                OCaml                                *)
(*                                                                     *)
(*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         *)
(*                                                                     *)
(*  Copyright 1996 Institut National de Recherche en Informatique et   *)
(*  en Automatique.  All rights reserved.  This file is distributed    *)
(*  under the terms of the Q Public License version 1.0.               *)
(*                                                                     *)
(***********************************************************************)

(* Performance test for I/O scheduling *)

let mut = Mutex.create()

let niter = ref 0

let token = ref 0

let process (n, ins, outs, nprocs) =
  let buf = String.make 1 '.' in
  while buf <> "-" do
    Unix.read ins.(n) buf 0 1;
    (* Printf.printf "Thread %d got the token\n" n; *)
    if n = 0 then begin
      decr niter;
      if !niter <= 0 then buf.[0] <- '-';
    end;
    let next = if n + 1 >= nprocs then 0 else n + 1 in
    (* Printf.printf "Thread %d sending token to thread %d\n" n next; *)
    Unix.write outs.(next) buf 0 1
  done

let main() =
  let nprocs = try int_of_string Sys.argv.(1) with _ -> 30 in
  let iter = try int_of_string Sys.argv.(2) with _ -> 1000 in
  let ins = Array.make nprocs Unix.stdin in
  let outs = Array.make nprocs Unix.stdout in
  let threads = Array.make nprocs (Thread.self ()) in
  for n = 0 to nprocs - 1 do
    let (i, o) = Unix.pipe() in ins.(n) <- i; outs.(n) <- o
  done;
  niter := iter;
  for i = 0 to nprocs - 1 do
    threads.(i) <- Thread.create process (i, ins, outs, nprocs)
  done;
  Unix.write outs.(0) "X" 0 1;
  for i = 0 to nprocs - 1 do Thread.join threads.(i) done

let _ = main()