GIL (Global Interpreter Lock) impact in Ruby - Time & Space Complexity
When running Ruby programs that use threads, the Global Interpreter Lock (GIL) affects how fast code runs.
We want to understand how the GIL changes the time it takes when using multiple threads.
Analyze the time complexity of this Ruby code using threads.
threads = []
5.times do
threads << Thread.new do
1_000_000.times { Math.sqrt(12345) }
end
end
threads.each(&:join)
This code runs 5 threads, each doing a million math calculations, then waits for all to finish.
Look at what repeats in the code.
- Primary operation: The loop inside each thread doing 1,000,000 math calculations.
- How many times: This loop runs 5 times in parallel threads.
Imagine increasing the number of threads or calculations.
| Input Size (threads) | Approx. Operations |
|---|---|
| 1 | 1,000,000 calculations |
| 5 | 5,000,000 calculations |
| 10 | 10,000,000 calculations |
Normally, more threads mean more work done at once, but the GIL makes threads wait, so total time grows closer to adding work, not speeding it up.
Time Complexity: O(n)
This means the total time grows roughly in direct proportion to the total work, even with multiple threads because the GIL limits true parallel execution.
[X] Wrong: "Adding more threads always makes the program run faster."
[OK] Correct: The GIL lets only one thread run Ruby code at a time, so threads often wait, limiting speed gains.
Understanding how the GIL affects threading shows you know how Ruby handles multiple tasks and helps you write better programs that use threads wisely.
"What if the threads mostly run code outside Ruby, like calling system commands? How would the GIL impact change then?"