From: Eric Hodel Date: 2012-07-06T05:22:38+09:00 Subject: Re: Green threads in 1.9.* ? On Jul 4, 2012, at 18:33, Tony Arcieri wrote: > On Wed, Jul 4, 2012 at 5:11 AM, Xavier Noria wrote: >> Then, behind the scenes, they are mapped to native threads in MRI 1.9 and JRuby. One-to-one. In the case of MRI there's a GIL. I guess technically a GIL does not mean that MRI is doing the scheduling, it means MRI is holding a lock, but the kernel schedules the native thread (because it is native). Maybe there's a gray area in the definition of green thread here, I don't know. > > MRI is still doing the scheduling in 1.9. It runs a timer thread that interrupts running threads after a certain amount of time so waiting threads can run. This way a single thread doing some computationally intensive operation doesn't monopolize the entire VM. A more accurate picture of 1.9 is: The OS schedules threads to run on CPUs. The ruby VM has a global lock that only allows one thread to run ruby code at a time (the GVL). The GVL is also held for execution inside C extensions unless the author releases the GVL (most extensions release the GVL for some part of their operation). Ruby schedules use of the GVL for threads created by the ruby VM. A Ruby thread may release the GVL to run non-ruby code. An example would be performing a long calculation such as interacting with a DB, processing zlib streams, XML parsing with libxml2, etc. Such tasks don't need to communicate with the ruby VM so they can be running on separate CPUs at the same time as the ruby VM. A Ruby thread will release the GVL when it performs a blocking operation such as IO or other system calls. So the OS and the ruby VM cooperate on thread scheduling. If multiple ruby threads do not need the GVL to run the OS does the majority of the scheduling. If multiple ruby threads do need the GVL ruby does the majority of the scheduling.