views:

49

answers:

1

Does ruby have the Java equivalent of synchronize keyword? I am using 1.9.1 and I don't quite see an elegant way to do this.

+7  A: 

It doesn't have the synchronize keyword, but you can get something very similar via the Monitor class. Here's an example from the Programming Ruby 1.8 book:

require 'monitor'

class Counter < Monitor
  attr_reader :count
  def initialize
    @count = 0
    super
  end

  def tick
    synchronize do
      @count += 1
    end
  end
end

c = Counter.new
t1 = Thread.new { 100_000.times { c.tick } }
t2 = Thread.new { 100_000.times { c.tick } }
t1.join; t2.join
c.count → 200000
Chris Bunch
This is BTW a general programming language design principle: only crappy programming languages need keywords or new language features for everything. Well-designed languages can do it simply in a library.
Jörg W Mittag
You also don't have to inherit from Monitor if you don't want to. Just include the MonitorMixin module (which also gets brought in by `require 'monitor'`) in your class and you get the same behavior for free.
Chuck