我知道红宝石的“合作”线程使用绿色线程。如何在我的应用程序中创建真正的“操作系统级”线程,以便使用多个cpu内核进行处理?
当前回答
如果您确实需要Ruby在产品级系统中的并行性(您不能使用beta),那么进程可能是更好的选择。 但是,首先在JRuby下尝试线程绝对是值得的。
另外,如果您对Ruby下线程的未来感兴趣,您可能会发现本文很有用。
其他回答
我将让“系统监视器”来回答这个问题。在这两种情况下,我用8个Ruby线程在i7(4个超线程核)机器上运行相同的代码(下面,计算质数)……第一次运行是:
Jruby 1.5.6 (ruby 1.8.7 patchlevel 249) (2014-02-03 6586) (OpenJDK 64-Bit Server VM 1.7.0_75) [amd64-java]
第二种是:
Ruby 2.2.1.p95 (2014-05-08) [x86_64-linux-gnu]
有趣的是,对于JRuby线程,CPU更高,但是对于解释后的Ruby,完成的时间略短。从图中很难看出这一点,但是第二次(解释的Ruby)运行使用了大约1/2的cpu(没有超线程?)
def eratosthenes(n)
nums = [nil, nil, *2..n]
(2..Math.sqrt(n)).each do |i|
(i**2..n).step(i){|m| nums[m] = nil} if nums[i]
end
nums.compact
end
MAX_PRIME=10000000
THREADS=8
threads = []
1.upto(THREADS) do |num|
puts "Starting thread #{num}"
threads[num]=Thread.new { eratosthenes MAX_PRIME }
end
1.upto(THREADS) do |num|
threads[num].join
end
如果您正在使用MRI,那么您可以用C编写线程代码作为扩展或使用ruby-inline gem。
使用drb怎么样?它不是真正的多线程,而是几个进程之间的通信,但你现在可以在1.8中使用它,而且它的阻力相当低。
因为不能编辑那个答案,所以在这里添加一个新的回答。
更新(2017-05-08)
这篇文章很旧了,信息也跟不上时代 (2017)胎面,以下是一些补充:
Opal is a Ruby to JavaScript source-to-source compiler. It also has an implementation of the Ruby corelib, It current very active develompent, and exist a great deal of (frontend) framework worked on it. and production ready. Because base on javascript, it not support parallel threads. truffleruby is a high performance implementation of the Ruby programming language. Built on the GraalVM by Oracle Labs,TruffleRuby is a fork of JRuby, combining it with code from the Rubinius project, and also containing code from the standard implementation of Ruby, MRI, still live development, not production ready. This version ruby seem like born for performance, I don't know if support parallel threads, but I think it should.
如果您确实需要Ruby在产品级系统中的并行性(您不能使用beta),那么进程可能是更好的选择。 但是,首先在JRuby下尝试线程绝对是值得的。
另外,如果您对Ruby下线程的未来感兴趣,您可能会发现本文很有用。
推荐文章
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何从线程捕获异常
- 列表是线程安全的吗?
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 每n秒运行特定代码
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 为什么这个Java程序会终止,尽管它显然不应该(也没有)终止?
- 最好的打印散列的方法
- 同步vs锁定
- 在ExecutorService的提交和执行之间进行选择
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- CountDownLatch是如何在Java多线程中使用的?