Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中运行多线程Open3调用_Ruby_Multithreading_Popen3 - Fatal编程技术网

在Ruby中运行多线程Open3调用

在Ruby中运行多线程Open3调用,ruby,multithreading,popen3,Ruby,Multithreading,Popen3,我有一个大循环,我试图在线程中运行对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 以下是线程版本:

我有一个大循环,我试图在线程中运行对
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)
每个线程应该独立运行,并且在访问数据方面没有死锁

你确定吗

threads << Thread.new do
  puts read(i)
end
对连续

output = Array.new(400) { |i| `echo Hello #{i}` }
# time: 0m0.794s

*事实上,这取决于几个因素。一些VM(JRuby)使用本机线程,并且更易于并行化。某些Ruby表达式比其他表达式更具并行性(取决于它们与GVL的交互方式)。确保并行性的最简单方法是运行单个外部命令,如子进程或系统调用,这些命令通常是无GVL的。

试试JRuby。它的螺纹没有损坏。
threads = Array.new(400) { |i| Thread.new { `echo Hello #{i}` } }
threads.each(&:join)
# time: 0m0.098s
output = Array.new(400) { |i| `echo Hello #{i}` }
# time: 0m0.794s