public
Last active

  • Download Gist
check_then_set_with_sheep_lock.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
class Sheep
def initialize
@shorn = false
# Here the sheep owns the mutex. But now the
# shearing logic is muddied up by synchronization
# logic. This doesn't seem like the right place for
# this.
@mutex = Mutex.new
end
 
def shorn?
@shorn
end
private :shorn?
 
def shear!
@mutex.synchronize do
return if shorn?
 
puts "shearing..."
@shorn = true
end
end
end
 
sheep = Sheep.new
 
# You could create the mutex here and let
# the threads fight over it before shearing
# the sheep, but it's just not necessary.
5.times.map do
Thread.new do
sheep.shear!
end
end.each(&:join)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.