LoginSignup
2
2

More than 5 years have passed since last update.

RubyでJavaのCountDownLatchを実装してみる

Posted at

テストコードで別スレッドの作業の完了待ち的な処理を行いたく、Rubyの標準ライブラリでJavaのCountDownLatch的なクラスは無いものかと探してみたものの見つからなかったので、試しにJava同じようなインターフェースでシンプル実装してみました。(実用には耐えないと思います)

class CountDownLatch
  def initialize(count)
    raise ArgumentError, 'count < 0' if count < 0
    @count = count
    @lock = Monitor.new
    @condition = @lock.new_cond
  end

  def count_down
    @lock.synchronize do
      @count -= 1 if @count > 0
      @condition.broadcast if @count == 0
    end
  end

  def await
    @lock.synchronize do
      @condition.wait if @count > 0
    end
  end
end

count = 10
latch = CountDownLatch.new(count)
t1 = Thread.new do
  latch.await
  puts 'Finished.'
end

t2 = Thread.new do
  count.times do |i|
    puts "Count #{i}"
    latch.count_down
  end
end

t1.join
t2.join

出力結果

Count 0
Count 1
Count 2
Count 3
Count 4
Count 5
Count 6
Count 7
Count 8
Count 9
Finished.
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2