返回顶部

收藏

Use monitor to lock

更多
require 'monitor' 
class Counter 
    attr_reader :count 

    def initialize 
        @count = 0 
    end 

    def tick 
        @count += 1 
    end 
end 

c = Counter.new 
lock = Monitor.new 

t1 = Thread.new { 10000.times { lock.synchronize { c.tick } } } 
t2 = Thread.new { 10000.times { lock.synchronize { c.tick } } } 
t1.join; t2.join 

c.count # 20000 

标签:Ruby,多线程

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2016-08-21 21:06:48use of Thread.stop, Thread.pass, and Thread.run: by 好好学习啊
  2. 2016-12-01 13:58:05Thread Priority by 胡晋
  3. 2016-08-21 21:23:32Try to interrupt a thread by LeoSun
  4. 2016-02-13 15:47:34Thread.abort_on_exception = true by jeffsui
  5. 2016-02-15 09:49:31Join a thread after sleeping by Jamin
  6. 2016-08-21 21:42:38Basic Ruby Threads in Action by 胡晋
  7. 2016-11-20 11:17:03Sleep amount of time by 永明
  8. 2016-03-20 17:32:10cede control from a thread by JustForFly
  9. 2016-08-21 21:58:30Run this block in a new thread by Ω油菜
  10. 2016-09-25 18:16:22Is it still alive, stopped by Jamin
  11. 2016-08-22 09:04:33Get the value returned from a thread by Ω油菜

发表评论