#!/usr/bin/env ruby
# $Source: /home/cvs/ESP/gen2/software/esp/example/threadTest.rb,v $
# $Id: threadTest.rb,v 1.12 2004/12/30 06:55:20 brent Exp $

require 'lock'

def threadTest (aSleepTime=nil, bSleepTime=nil)

  # declare new lock toy with signals called goahead and phase2
  toy = Lock :toy,
         :goahead, :phase2, :start

  a = Thread (:A) {
    puts "A:  Nothing's synchronized yet"
    puts "A:  I'm playing with my toy, but I'll give it up"
    puts "A:  until I receive the :goahead signal"
    toy.signal(:start).await :goahead
    puts "A:  Got the :goahead signal. I have my toy again!  I rule!"
    puts "A:  Now I will tell the other thread to that phase2 is complete"
    sleep aSleepTime if aSleepTime
    toy.signal(:phase2).await :phase2
    puts "A:  Got :phase2 signal"
  }


  b = Thread (:B) {
    puts "B:  Nothing's synchronized yet"
    toy.lock do
      puts "B:  got Toy!"
      toy.await :start
      puts "B:  Got :start."
      puts "B:  But I'll let the other thread know when it can proceed."
      puts "B:  by sending the :goahead signal"
      sleep bSleepTime if bSleepTime
      toy.signal (:goahead).await :phase2
      puts "B:  Got the toy back!  Completed :phase2"
      toy.signal :phase2
    end
  }
  a.join
  b.join
  puts "both child threads have completed"
  
end

p ((ARGV[0]?(ARGV[0].to_i):1).times {threadTest}) if $0 == __FILE__


