# $Id: prodcons.pliant,v 1.0 2002/02/25 11:58:00 dada Exp $
# http://dada.perl.it/shootout/

module "/pliant/language/context.pli"

gvar Sem s
gvar Int count := 0
gvar Int data := 0
gvar Int produced := 0
gvar Int consumed := 0
gvar Int done := 0

function consumer n
  arg Int n
  var Int i
  part forever
    part consumer_wait
      if(count = 0)
        restart consumer_wait
      leave consumer_wait
    i := data
    count := 0
    # console "consuming " i eol
    consumed := consumed + 1
    if (i = n)
      leave forever
    restart forever

function producer n
  arg Int n
  for (var Int i) 1 n
    part producer_wait
      if(count = 1)
        restart producer_wait
      leave producer_wait
    data := i
    count := 1
    # console "producing " i eol
    produced := produced + 1
  done := 1

gvar Str s_n := cast ((pliant_script_args translate Address 1) map CStr) Str
if (s_n parse (gvar Int n))
  thread
    # console "starting producer thread..." eol
    share produced
    share data
    share count
    share s
    share done
    producer n
  thread
    # console "starting consumer thread..." eol  
    share consumed
    share data
    share count
    share s 
    consumer n
  part wait_done
    if (done = 1)
      leave wait_done      
    restart wait_done  
  console produced " " consumed eol
  s release
else
  console "usage: prodcons.pliant <number>" eol