What are green threads?
sobes.tech AI
Answer from AI
Green threads are user-space managed threads, not managed directly by the operating system. They are not directly mapped to OS threads. Scheduling and context switching between green threads are handled by the language runtime or a special library.
Main characteristics:
- Management: Fully handled by the runtime.
- Resources: Require fewer system resources (memory and CPU time) compared to native OS threads for creation and switching.
- Scheduling: Cooperative multitasking. A thread must explicitly yield control for another green thread to run.
- Parallelism: Due to non-preemptive scheduling and user-space management, green threads do not inherently support parallel execution on multi-core processors without additional mechanisms (e.g., using multiple processes, each with its own green threads).
In Ruby, especially in older versions (before 1.9) and with MRI (Matz's Ruby Interpreter), green threads were used. This led to performance issues on multi-core systems, as only one green thread could run at any given time, blocked by the Global Interpreter Lock (GIL). Later versions of MRI and alternative implementations (JRuby, Rubinius) use native OS threads.
# Example of using threads in Ruby (depending on version and implementation, these can be green or native)
t1 = Thread.new do
puts "Thread 1 started"
sleep(1)
puts "Thread 1 finished"
end
t2 = Thread.new do
puts "Thread 2 started"
sleep(1)
puts "Thread 2 finished"
end
t1.join # Waits for thread t1 to finish
t2.join # Waits for thread t2 to finish
puts "All threads finished"
Comparison of green and native threads:
| Characteristic | Green threads | Native OS threads |
|---|---|---|
| Management | User space | OS kernel |
| Creation/Switching | Cheaper | More expensive |
| Scheduling | Cooperative (non-preemptive) | Preemptive |
| Parallelism | Limited (single CPU) without mechanisms | Full (multi-CPU) |
| Blocking calls | Block the entire interpreter/process | Block only the current native thread |
In the context of modern Ruby (from 1.9 and above MRI), the standard Thread is a native OS thread. Green threads, as the main concurrency model, are now rare in MRI but may still appear in specific libraries or alternative runtimes.