Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Ruby | Mutex | locked?

概要

Mutex#locked? -> bool

詳細

mutex がロックされている時、真を返却。

サンプルコード
require "thread"

class Counter
  attr_reader :count
  def initialize
    @count = 0
    @m = Mutex.new
  end

  def increment(id)
    puts "id = #{id}, locked? = #{@m.locked?}"
    @m.lock
    puts "id = #{id}, locked? = #{@m.locked?}"
    begin
      puts "inner lock #{id}"
      @count += 1
      sleep rand(5)
    ensure
      @m.unlock
    end
  end

  def locked?
    @m.locked?
  end
end

counter = Counter.new

threads = [*1..5].map do |i|
  Thread.new do |t|
    counter.increment(i)
    puts counter.count
  end
end

threads.each(&:join)

出力

$ ruby mutex_locked.rb
id = 3, locked? = false
id = 1, locked? = false
id = 3, locked? = true
id = 5, locked? = true
id = 4, locked? = true
id = 2, locked? = false
inner lock 3
1
id = 5, locked? = true
inner lock 5
2
id = 4, locked? = true
inner lock 4
3
id = 2, locked? = true
inner lock 2
4
id = 1, locked? = true
inner lock 1
5