我有一个大循环,我试图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