Forked from jstorimer/check_then_set_with_sheep_lock.rb
Last active
August 29, 2015 14:23
-
-
Save rayning0/70ae1ba01bba78040051 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
# http://www.rubyinside.com/does-the-gil-make-your-ruby-code-thread-safe-6051.html | |
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) | |
#--------------------------------------- | |
# Better way to do sychonization and avoid race conditions. Use a queue: | |
class Sheep | |
def initialize | |
@shorn = false | |
end | |
def shorn? | |
@shorn | |
end | |
def shear! | |
return if shorn? | |
puts "shearing..." | |
@shorn = true | |
end | |
end | |
sheep = Sheep.new | |
sheep_queue = Queue.new | |
sheep_queue << sheep | |
5.times.map do | |
Thread.new do | |
begin | |
sheep = sheep_queue.pop(true) | |
sheep.shear! | |
rescue ThreadError | |
end | |
end | |
end.each(&:join) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment