Last active
March 5, 2019 13:34
-
-
Save jenny-codes/2e3147cd595badab6a16a0067ec822d5 to your computer and use it in GitHub Desktop.
Use Mutex to avoid involuntary context switch in Ruby.
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
def send_money(amount) | |
puts "Sending $#{amount}" | |
sleep 1 # Simulate network call sending of money | |
end | |
lock = Mutex.new | |
threads = [] | |
money_is_sent = false | |
2.times do | |
th = Thread.new do | |
lock.synchronize { # DO NOT USE 'Mutex.new.synchronize' | |
unless money_is_sent | |
send_money 10 | |
money_is_sent = true | |
end | |
} | |
end | |
threads << th | |
end | |
ThWait.all_waits(*threads) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment