Sobes.tech
Middle+

What is GVL (Global VM Lock) in Ruby?

sobes.tech AI

Answer from AI

GVL (Global VM Lock) is a mechanism in the standard implementation of Ruby (CRuby) that allows only one thread to execute in the Ruby interpreter at any given time.

  • Purpose: To simplify the implementation of the interpreter, memory management, and prevent race conditions in a multithreaded environment without using complex object-level locks.

  • Impact: It limits true parallelism when executing CPU-bound tasks on multiprocessor systems, as only one thread can execute Ruby code.

  • Releasing GVL: GVL is temporarily released during I/O operations such as reading from a file or network requests. This allows other threads to execute Ruby code while one thread waits for I/O to complete.

  • Alternatives: JRuby, Rubinius (do not have GVL, use native locks, and perform garbage collection at the Java VM or LLVM level).

# Example of using threads in Ruby
thread1 = Thread.new { 1000000.times { 1 + 1 } } # CPU-bound
thread2 = Thread.new { puts "Hello" }           # I/O-bound (can run while thread1 waits)

thread1.join
thread2.join