1

If you want to lock methods on instances, you have to create a Mutex for every instance and method:

class Foo
  def initialize
    @blue_mutex = Mutex.new
    @red_mutex = Mutex.new
  end

  def blue
    @blue || @blue_mutex.synchronize do
      @blue ||= Blue.new
    end
  end

  def red_mutex
    @red || @red_mutex.synchronize do
      @red ||= Red.new
    end
  end
end

Is there a logical error with having Thread.exclusive take arguments?

class Foo
  def blue
    @blue || Thread.exclusive("#{object_id}/blue") do
      @blue ||= Blue.new
    end
  end

  def red
    @red || Thread.exclusive("#{object_id}/red") do
      @red ||= Red.new
    end
  end
end

Why create mutexes if Thread.exclusive could just take an argument that defines the scope of the exclusivity?

Seamus Abshere
  • 8,326
  • 4
  • 44
  • 61

1 Answers1

0

The short answer is that the API could be done the way you describe. In fact that is what Java does by letting you lock an arbitrary object. It has to play tricks because the tracking of the lock uses up some reserved space on the object itself. Also, when the object is locked and becomes contended, a real mutex has to be created, which uses some more space. But hopefully your code isn't littered with objects being locked and unlocked. My guess is that the Ruby creators didn't want to burden every object with this extra functionality that would only be used infrequently.

I assumed above that when you said "clunky" you were referring to the readability of the code. If you are concerned about performance, I doubt there is much difference. Under the covers either approach can use the same, very efficient technique. It's just a question of the extra memory to store the thin locks on each object. I found some interesting details about that here

Community
  • 1
  • 1
John Watts
  • 8,717
  • 1
  • 31
  • 35
  • John, thanks. I'm going to wait a few more days to see if I can get an answer pointing to historical discussions in or the current mindset of the ruby community, but otherwise your answer is great. – Seamus Abshere Jun 11 '12 at 15:04