Friday, August 24, 2012

Ruby Semaphore

Ruby uses the Mutex Class to provide semaphore lock for mutually exclusive access to shared resource.
Example from ruby-doc.org:

Without Semaphore:

count1 = count2 = 0
difference = 0
counter = Thread.new do
  loop do
    count1 += 1
    count2 += 1
  end
end
spy = Thread.new do
  loop do
    difference += (count1 - count2).abs
  end
end
sleep 1
Thread.critical = 1
count1    »    184846
count2    »    184846
difference    »    58126


With Semaphore:


require 'thread'
mutex = Mutex.new

count1 = count2 = 0
difference = 0
counter = Thread.new do
  loop do
    mutex.synchronize do
      count1 += 1
      count2 += 1
    end
  end
end
spy = Thread.new do
  loop do
    mutex.synchronize do
      difference += (count1 - count2).abs
    end
  end
end
sleep 1
mutex.lock
count1    »    21192
count2    »    21192
difference    »    0

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.