0
0
Rubyprogramming~7 mins

Thread synchronization with Mutex in Ruby

Choose your learning style9 modes available
Introduction

Mutex helps threads take turns so they don't mess up shared data. It keeps things safe and organized.

When multiple threads need to update the same bank account balance.
When threads write to the same file and you want to avoid mixed-up content.
When you have a shared list and threads add or remove items from it.
When you want to make sure only one thread changes a setting at a time.
Syntax
Ruby
mutex = Mutex.new
mutex.synchronize do
  # critical section code here
end

The Mutex.new creates a new lock.

The synchronize method makes sure only one thread runs the code inside at a time.

Examples
This example locks the code that prints a message so only one thread can print at once.
Ruby
mutex = Mutex.new
mutex.synchronize do
  puts "Only one thread here!"
end
Multiple threads safely increase count using the mutex to avoid mistakes.
Ruby
mutex = Mutex.new
count = 0
threads = 5.times.map do
  Thread.new do
    mutex.synchronize do
      count += 1
    end
  end
end
threads.each(&:join)
puts count
Sample Program

This program creates 10 threads. Each thread adds 1 to counter 1000 times. The mutex makes sure the counter updates safely without errors.

Ruby
mutex = Mutex.new
counter = 0
threads = 10.times.map do
  Thread.new do
    1000.times do
      mutex.synchronize do
        counter += 1
      end
    end
  end
end
threads.each(&:join)
puts "Final counter value: #{counter}"
OutputSuccess
Important Notes

Always use mutex.synchronize to wrap code that changes shared data.

Without mutex, threads can overwrite each other's changes, causing wrong results.

Mutex only locks one thread at a time; others wait patiently.

Summary

Mutex helps threads work together without breaking shared data.

Use mutex.synchronize to protect critical code sections.

Thread synchronization avoids bugs from simultaneous changes.