Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Ruby thread demo not use both cores?

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]
like image 448
Nick Bolton Avatar asked Aug 06 '10 19:08

Nick Bolton


2 Answers

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.

like image 101
Jörg W Mittag Avatar answered Nov 09 '22 09:11

Jörg W Mittag


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.

like image 20
Zifei Tong Avatar answered Nov 09 '22 09:11

Zifei Tong