Skip to content

Instantly share code, notes, and snippets.

@jenny-codes
Last active March 5, 2019 13:34
Show Gist options
  • Save jenny-codes/2e3147cd595badab6a16a0067ec822d5 to your computer and use it in GitHub Desktop.
Save jenny-codes/2e3147cd595badab6a16a0067ec822d5 to your computer and use it in GitHub Desktop.
Use Mutex to avoid involuntary context switch in Ruby.
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