【发布时间】:2019-06-05 12:55:27
【问题描述】:
我有一个大循环,我试图在线程中运行对Open3.capture3 的调用,而不是线性运行。每个线程都应该独立运行,并且在访问数据方面没有死锁。
问题是,线程版本太慢了,占用了我的 CPU。
这是一个线性规划的例子:
require 'open3'
def read(i)
text, _, _ = Open3.capture3("echo Hello #{i}")
text.strip
end
(1..400).each do |i|
puts read(i)
end
这是线程版本:
require 'open3'
require 'thread'
def read(i)
text, _, _ = Open3.capture3("echo Hello #{i}")
text.strip
end
threads = []
(1..400).each do |i|
threads << Thread.new do
puts read(i)
end
end
threads.each(&:join)
时间比较:
$ time ruby linear.rb
ruby linear.rb 0.36s user 0.12s system 110% cpu 0.433 total
------------------------------------------------------------
$ time ruby threaded.rb
ruby threaded.rb 1.05s user 0.64s system 129% cpu 1.307 total
【问题讨论】:
-
试用 JRuby。它的线没有残废。
标签: ruby multithreading popen3