Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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