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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment