What does synchronize do

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

Here's a very simple example from a multi-threaded bank account system where we want to stop race conditions from potentially letting someone transfer more money than they have.

require 'thread'

# A BankAccount has a checking amount and a savings amount
class BankAccount
  def initialize(checking, savings)
    @checking,@savings = checking, savings
    @mutex = Mutex.new  # For thread safety
  end

# Lock account and transfer money from savings to checking
def transfer_from_savings(x)
  @mutex.synchronize {
    @savings -= x
    @checking += x
  }
  end
end

This ensures that the critical code is only run by 1 thread at a time.