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.
GIL (Global Interpreter Lock) impact in 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.
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
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"
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.
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
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.
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.