ruby线程同步

   脚本:【线程同步类】
 
   功能:对使用ruby多线程编程时,对临界资源进行同步操作的类。
 
   说明: 对于不同线程访问临界资源(公共变量等)时,应进行同步。
 
         步骤:
         1、创建Mutex对象;
         2、在线程内要访问临界资源的地方调用Mutex(互斥)对象的同步方法进行同步。
       
         e.g.: lock = Mutex.new
       
                lock.synchronize{
                  # 中间即要同步的块
                }

   作者:灼眼的夏娜
 
   版本:v1.0。

=end

#================================================================
# ■ Mutex
#------------------------------------------------------------------------------
#  互斥锁的类。
#================================================================
class Mutex
 
   #--------------------------------------------------------------------------
   # ● 初始化
   #--------------------------------------------------------------------------
   def initialize
     @synchronizing = false
     @waiting_threads = Array.new
   end
 
   #--------------------------------------------------------------------------
   # ● 同步块
   #--------------------------------------------------------------------------
   def synchronize
     Thread.critical = true
     if @synchronizing
       @waiting_threads << Thread.current
       Thread.stop
     end
     @synchronizing = true
     Thread.critical = false
     yield
     Thread.critical = true
     next_thread = @waiting_threads.shift
     if next_thread.nil?
       @synchronizing = false
     else
       next_thread.run
     end
     Thread.critical = false
   end
 
end

以下举例:

1、未同步的情况:

apples = 5

t1 = Thread.new do
   while true
     if apples > 0
       sleep(0.001)
       p "Thread01 get the #{6 - apples}th apple."
       apples -= 1
       if apples == 0
         break
       end
     end
   end
end

t2 = 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
   end
end

可以看到线程01得到了第六个苹果- -bb,显然出错了。

2、同步的情况:

apples = 5

mu_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
   end
end

t2 = 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
   end
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值