[Code: ]
require 'thread'
mutex = Mutex.new
conditionVariable=ConditionVariable.new
speed=0
flag=false
police=Thread.new(10) do |value|
value.times do |i|
mutex.lock
if (speed==0)
puts "Police: please keep this speed, let me check your speed"
conditionVariable.wait(mutex)
end
if flag then
puts "The taxi's speed is #{speed}m/s, pass the check"
puts "_____________________"
flag=false
speed=0
conditionVariable.signal
else
conditionVariable.wait(mutex)
end
mutex.unlock
end
end
people=Thread.new(10) do |value|
value.times do |i|
mutex.lock
if !flag then
speed=rand(100)
puts "Shop #{speed}"
flag=true
conditionVariable.signal
else
conditionVariable.wait(mutex)
end
mutex.unlock
end
end
people.join
[Expected Result:]
Shop 55
The taxi's speed is 55m/s, pass the check
_____________________
Police: please keep this speed, let me check your speed
Shop 49
The taxi's speed is 49m/s, pass the check
_____________________
Police: please keep this speed, let me check your speed
Shop 22
The taxi's speed is 22m/s, pass the check
_____________________
Police: please keep this speed, let me check your speed
Shop 91
The taxi's speed is 91m/s, pass the check
_____________________
Police: please keep this speed, let me check your speed
Shop 36
The taxi's speed is 36m/s, pass the check
_____________________
Police: please keep this speed, let me check your speed