#==============================================================================# ■ Mutex#------------------------------------------------------------------------------# 互斥锁的类。#==============================================================================class Mutex #-------------------------------------------------------------------------- # ● 初始化 #-------------------------------------------------------------------------- def initialize @synchronizing = false @waiting_threads = Array.new end #-------------------------------------------------------------------------- # ● 同步块 #-------------------------------------------------------------------------- def synchronize Thread.critical = true if @synchronizing @waiting_threads 0 sleep(0.001) p "Thread01 get the #{6 - apples}th apple." apples -= 1 if apples == 0 break end end endendt2 = Thread.new do while true if apples > 0 sleep(0.001) p "Thread02 get the #{6 - apples}th apple." apples -= 1 if apples == 0 break end end endend复制代码
复制代码
可以看到线程01得到了第六个苹果- -bb,显然出错了。
2、同步的情况:
apples = 5mu_obj = Mutex.new # 创建互斥对象t1 = Thread.new do while true mu_obj.synchronize do # 同步块 if apples > 0 sleep(0.001) p "Thread01 get the #{6 - apples}th apple." apples -= 1 if apples == 0 break end end end endendt2 = Thread.new do while true mu_obj.synchronize do # 同步块 if apples > 0 sleep(0.001) p "Thread02 get the #{6 - apples}th apple." apples -= 1 if apples == 0 break end end end endend复制代码