Last active
July 2, 2017 22:03
-
-
Save jstorimer/5802725 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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