使用ConditionVariable类实现同步

[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值