Web 应用大多是 IO 密集型的,利用 Ruby 多进程+多线程模型将能大幅提升系统吞吐量。其原因在于:当Ruby 某个线程处于 IO Block 状态时,其它的线程还可以继续执行。但由于存在 Ruby GIL (Global Interpreter Lock),MRI Ruby 并不能真正利用多线程进行并行计算。JRuby 去除了 GIL,是真正意义的多线程,既能应付 IO Block,也能充分利用多核 CPU 加快整体运算速度。
上面说得比较抽象,下面就用例子一一加以说明。
Ruby 多线程和 IO Block
先看下面一段代码(演示目的,没有实际用途):
代码如下:
# File: block_io1.rb
def func1
puts "sleep 3 seconds in func1/n"
sleep(3)
end
def func2
puts "sleep 2 seconds in func2/n"
sleep(2)
end
def func3
puts "sleep 5 seconds in func3/n"
sleep(5)
end
func1
func2
func3
代码很简单,3 个方法,用 sleep 模拟耗时的 IO 操作。 运行代码(环境 MRI Ruby 1.9.3) 结果是:
代码如下:
$ time ruby block_io1.rb
sleep 3 seconds in func1
sleep 2 seconds in func2
sleep 5 seconds in func3
real 0m11.681s
user 0m3.086s
sys 0m0.152s
比较慢,时间都耗在 sleep 上了,总共花了 10 多秒。
采用多线程的方式,改写如下:
代码如下:
# File: block_io2.rb
def func1
puts "sleep 3 seconds in func1/n"
sleep(3)
end
def func2
puts "sleep 2 seconds in func2/n"
sleep(2)
end
def func3
puts "sleep 5 seconds in func3/n"
sleep(5)
end
threads = []
threads << Thread.new { func1 }
threads << Thread.new { func2 }
threads << Thread.new { func3 }
threads.each { |t| t.join }
运行的结果是:
代码如下:
$ time ruby block_io2.rb
sleep 3 seconds in func1
sleep 2 seconds in func2
sleep 5 seconds in func3
real 0m6.543s
user 0m3.169s
sys 0m0.147s
总共花了 6 秒多,明显快了许多,只比最长的 sleep 5 秒多了一点。
上面的例子说明,Ruby 的多线程能够应付 IO Block,当某个线程处于 IO Block 状态时,其它的线程还可以继续执行,从而使整体处理时间大幅缩短。
Ruby GIL 的影响
还是先看一段代码(演示目的):
代码如下:
# File: gil1.rb
require 'securerandom'
require 'zlib'
data = SecureRandom.hex(4096000)
16.times { Zlib::Deflate.deflate(data) }
代码先随机生成一些数据,然后对其进行压缩,压缩是非常耗 CPU 的,在我机器(双核 CPU, MRI Ruby 1.9.3)运行结果如下:
代码如下:
$ time ruby gil1.rb
real 0m8.572s
新闻热点
疑难解答