Skip to content

Instantly share code, notes, and snippets.

@jstorimer
Last active July 2, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jstorimer/5802725 to your computer and use it in GitHub Desktop.
Save jstorimer/5802725 to your computer and use it in GitHub Desktop.
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