0
0
Rubyprogramming~5 mins

Thread safety concepts in Ruby

Choose your learning style9 modes available
Introduction

Thread safety means making sure that when multiple parts of a program run at the same time, they do not cause errors or unexpected results.

When your program uses multiple threads to do tasks at the same time.
When you share data between threads and want to avoid mistakes.
When you want your program to run faster by doing things in parallel safely.
When you want to prevent crashes caused by threads changing data at the same time.
Syntax
Ruby
# Use Mutex to make code thread-safe
mutex = Mutex.new
mutex.synchronize do
  # critical section code here
end
Mutex is a tool that lets only one thread run a piece of code at a time.
Use mutex.synchronize to wrap code that changes shared data.
Examples
This example uses a mutex to safely increase a counter from multiple threads.
Ruby
mutex = Mutex.new
counter = 0
threads = []
5.times do
  threads << Thread.new do
    1000.times do
      mutex.synchronize { counter += 1 }
    end
  end
end
threads.each(&:join)
puts counter
This example does not use a mutex, so the counter may have wrong value due to race conditions.
Ruby
counter = 0
threads = []
5.times do
  threads << Thread.new do
    1000.times { counter += 1 } # Not thread-safe
  end
end
threads.each(&:join)
puts counter
Sample Program

This program creates 5 threads. Each thread adds 1 to the counter 1000 times. Using a mutex ensures the counter is updated safely without errors.

Ruby
require 'thread'

mutex = Mutex.new
counter = 0
threads = []

5.times do
  threads << 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

Without thread safety, shared data can get corrupted or cause crashes.

Mutex is the most common way to protect shared data in Ruby threads.

Always keep the critical section (code inside synchronize) as short as possible to avoid slowing down your program.

Summary

Thread safety prevents errors when multiple threads access shared data.

Use Mutex and synchronize to protect critical code sections.

Proper thread safety helps programs run correctly and faster with multiple threads.