File: ex2.ml

package info (click to toggle)
ocamlmakefile 6.39.2-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 336 kB
  • sloc: ml: 182; makefile: 57; sh: 7; ansic: 7
file content (28 lines) | stat: -rw-r--r-- 688 bytes parent folder | download | duplicates (10)
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
open Printf
open Thread

let rec integers n ch =
  Event.sync (Event.send ch n);
  integers (n+1) ch

let rec sieve n chin chout =
  let m = Event.sync (Event.receive chin) in
  if m mod n = 0 then sieve n chin chout
  else (Event.sync (Event.send chout m); sieve n chin chout)

let rec print_primes ch max =
  let n = Event.sync (Event.receive ch) in
  if n > max then ()
  else begin
    printf "%d\n" n; flush stdout;
    let ch_after_n = Event.new_channel () in
    ignore (Thread.create (sieve n ch) ch_after_n);
    print_primes ch_after_n max
  end

let go max =
  let ch = Event.new_channel () in
  ignore (Thread.create (integers 2) ch);
  print_primes ch max;;

let _ = go 1000