Hopefully this screenshot will explain my question:
a = Thread.new { loop {} }
b = Thread.new { loop {} }
a.join
Ruby threads demo CPU usage http://img7.imageshack.us/img7/9858/rubycores.png
So how come both of my cores aren't maxed out? No matter how many threads I use, it's the same each time; the total CPU usage never seems to exceed 52%.
>ruby -v
ruby 1.8.6 (2010-02-04 patchlevel 398) [i386-mingw32]
It looks like you are using MRI, which is incapable of running threads in parallel. At the moment, the only production-ready Ruby implementations which can run threads in parallel are JRuby and IronRuby.
Remember, if you want threads to actually run in parallel, then every layer in the stack must be able to do that. Take JRuby, for example: JRuby can run Ruby threads in parallel. However, it implements threads by mapping them to JVM threads, so if the JVM is incapable of running threads in parallel (and there are some for which this is the case), then the fact that JRuby can run Ruby threads in parallel doesn't help you one bit. Many JVMs, in turn, map JVM threads to OS threads. And again: if the OS isn't capable of running threads in parallel, there's nothing the JVM can do. And last but not least: if there's only one processor, the whole exercise is pointless anyway.
I think this answer is awesome.
Does ruby have real multithreading?
Since your are using Ruby 1.8.6, the MRI Implementation. This quotation form the URL above explain why only one core is used.
MRI implements Ruby Threads as Green Threads within its interpreter. Unfortunately, it doesn't allow those threads to be scheduled in parallel, they can only run one thread at a time.
Note that MacRuby (sort of a port of YARV) removed the GIL recently. So your demo code will use both cores with MacRuby 0.5 or later version. For now it is the only Ruby Implementation that can run in parallel that not depending on JVM or CLR.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With