Skip to content

Instantly share code, notes, and snippets.

@jenny-codes
Last active March 5, 2019 13:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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