Download pseudo source code

 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
procedure main(argc, argv[]):
  if argc = 7 then
    shared buffer_capacity := integer(argv[1])
    shared buffer as array of buffer_capacity of float
    shared rounds := integer(argv[2])
    shared producer_min_delay := integer(argv[3])
    shared producer_max_delay := integer(argv[4])
    shared consumer_min_delay := integer(argv[5])
    shared consumer_max_delay := integer(argv[6])

    shared can_produce := create_semaphore(buffer_capacity)
    shared can_consume := create_semaphore(0)

    create_threads(1, produce)
    create_threads(1, consume)
  end if
end procedure

procedure produce:
  declare count := 0
  for round := 1 to rounds do
    for index := 0 to buffer_capacity do
      wait(can_produce)
      delay(random_between(producer_min_delay, producer_max_delay))
      buffer[index] := ++count
      print("Produced ", buffer[index])
      signal(can_consume)
    end for
  end for
end procedure

procedure consume:
  for round := 1 to rounds do
    for index := 0 to buffer_capacity do
      wait(can_consume)
      value := buffer[index]
      delay(random_between(consumer_min_delay, consumer_max_delay))
      print("Consumed ", value)
      signal(can_produce)
    end for
  end for
end procedure

function random_between(min, max):
  return min + rand() % (max - min)
end function