Fix for JRUBY-2882. Handle error messages related to constructors better
[jruby.git] / bench / shootout / chameneos.ruby-2.ruby
blob4e680024f33e3a6b71b2aa22a83159b126010249
1 #########################################
2 # The Computer Language Shootout #
3 # http://shootout.alioth.debian.org/ #
4 # #
5 # Contributed by Jesse Millikan #
6 # Based on version by Gordon Innes #
7 #########################################
9 require 'thread'
11 creature_meetings = Queue.new
12 meeting_point = Mutex.new
13 wait_signal = ConditionVariable.new
14 meetings_left = ARGV[0].to_i
15 waiting_colour, incoming_colour = nil, nil
17 # Each chameneo is represented here by a thread
18 # and its colour variable, rather than explicitly
19 # by an object
21 # This is all packed into one place for speed and
22 # clarity (It's clear to *me* :)
23 [:blue, :red, :yellow, :blue].each { |colour|
24 Thread.new {
25 met = 0
26 while true
27 # The form meeting_point.synchronize { } is slow
28 meeting_point.lock
30 if meetings_left <= 0
31 meeting_point.unlock
32 # colour = :faded
33 break
34 end
36 # Both threads emerge with variable other_colour set
37 if waiting_colour
38 other_colour = waiting_colour
39 incoming_colour = colour
40 wait_signal.signal
41 meetings_left-=1
42 waiting_colour = nil
43 else
44 waiting_colour = colour
45 wait_signal.wait(meeting_point)
46 other_colour = incoming_colour
47 end
48 meeting_point.unlock
50 met += 1
52 # Take the complement colour
53 colour =
54 case other_colour
55 when :blue
56 colour == :red ? :yellow : :red
57 when :red
58 colour == :blue ? :yellow : :blue
59 when :yellow
60 colour == :blue ? :red : :blue
61 end
62 end
64 # Leave the total on the queue for the main thread
65 creature_meetings.push(met)
69 total = 0
70 4.times { total += creature_meetings.pop }
71 puts total