0
0
Rubyprogramming~5 mins

GIL (Global Interpreter Lock) impact in Ruby

Choose your learning style9 modes available
Introduction

The Global Interpreter Lock (GIL) is a mechanism that makes sure only one thread runs Ruby code at a time. This helps avoid problems but can slow down programs that try to do many things at once.

When you want to run multiple tasks at the same time in Ruby using threads.
When you notice your Ruby program is not getting faster even with multiple CPU cores.
When you want to understand why some Ruby programs don't speed up with threads.
When you plan to use Ruby threads for tasks like web servers or background jobs.
When you want to decide between using threads or processes in Ruby.
Syntax
Ruby
# Ruby threads example
thread = Thread.new do
  # code to run in new thread
end
thread.join

Ruby threads run inside the same process but the GIL allows only one thread to execute Ruby code at a time.

This means threads can help with waiting tasks but not with heavy CPU work.

Examples
This example runs two threads that print messages. They run one at a time because of the GIL, but switching happens fast.
Ruby
thread1 = Thread.new { 5.times { puts "Thread 1 working"; sleep 0.1 } }
thread2 = Thread.new { 5.times { puts "Thread 2 working"; sleep 0.1 } }
thread1.join
thread2.join
This example shows that using threads for heavy math doesn't speed up much because of the GIL.
Ruby
require 'benchmark'

result = Benchmark.measure do
  threads = 4.times.map do
    Thread.new do
      sum = 0
      10_000_000.times { sum += 1 }
    end
  end
  threads.each(&:join)
end

puts "Time taken: #{result.real} seconds"
Sample Program

This program creates two threads that print counts with pauses. Because of the GIL, only one thread runs Ruby code at a time, but they switch quickly, so output is mixed.

Ruby
thread1 = Thread.new do
  3.times do |i|
    puts "Thread 1: Count #{i + 1}"
    sleep 0.2
  end
end

thread2 = Thread.new do
  3.times do |i|
    puts "Thread 2: Count #{i + 1}"
    sleep 0.2
  end
end

thread1.join
thread2.join
OutputSuccess
Important Notes

The GIL prevents true parallel execution of Ruby code in threads.

Threads are still useful for tasks that wait for input/output, like reading files or network calls.

For CPU-heavy tasks, using multiple Ruby processes or other tools can help use multiple CPU cores.

Summary

The GIL lets only one Ruby thread run code at a time.

This can slow down programs that try to do many CPU tasks at once with threads.

Threads are still good for tasks that wait, like network or file operations.