【问题标题】:How do you iterate over ARGV and create a Thread for each value in the array in Ruby您如何遍历 ARGV 并为 Ruby 中数组中的每个值创建一个线程
【发布时间】:2016-09-22 04:15:34
【问题描述】:

我正在尝试创建一个 Ruby 脚本,为 ARGV 中传递的每个参数启动一个单独的线程,但我不知道如何迭代它们并将它们作为常量(或线程-安全的)。比如:

编译.rb

require 'rubygems'
require 'compass'
require 'compass/exec'

threads = []
ARGV.each do |arg|
  threads << Thread.new { Compass::Exec::SubCommandUI.new(["compile", arg]).run! }
end
threads.each { |thr| thr.join }

结果是它会创建预期数量的线程,但每个线程将在相同的 arg 值上运行(循环不会按预期工作)。

我正在尝试从 Ant 运行它,如下所示:

build.xml

<java fork="true" failonerror="true" classpathref="jruby.classpath" classname="org.jruby.Main">
    <arg path="${ext.path}\compile.rb"></arg>
    <arg line="${config.rb.dirs.str}"></arg>
</java>

其中“config.rb.dirs.str”包含我到多个 Sass 项目的路径,以空格分隔。

我是 Ruby 的新手,所以请不要评判。谢谢!

【问题讨论】:

  • "每个线程都将在相同的 arg 值上运行" -- 我不明白为什么会发生这种情况;你的代码对我来说看起来不错。你是如何运行脚本的? (你在控制台输入什么命令?)
  • 我编辑了问题,将我的 java 回调包含在 Ant 中,用于调用 ruby​​ 脚本
  • 这很奇怪,因为如果我只是在线程内执行“打印 arg”,那效果很好,这让我认为问题出在 Compass::Exec::SubCommandUI 并行运行。
  • ARGV 实际上等于什么?是["arg1", "arg2", "arg3"],还是["arg1 arg2 arg3"]?使用p ARGVputs ARGV.inspect 查看。我的怀疑&lt;arg line="..." 将所有内容都塞进了一个论点,但如果没有更多信息,我不能说。
  • 我试过p ARGVputs ARGV.inspect,它们都输出["arg1", "arg2", "arg3"]

标签: ruby multithreading sass compass-sass compass


【解决方案1】:

您可以运行以下命令并告诉我们输出吗? 您可以使用 args 运行它,也可以使用脚本中指定的默认 args。 这只是传递变量的两种方式(我更喜欢第二种)。我认为这是一个不需要任何额外内容的最小样本。

args = ARGV.size > 0 ? ARGV : ['arg1', 'arg2', 'arg3']

puts "args is #{args} and has size #{args.size}"
threads = args.map do |arg|
  Thread.new do
    sleep 1
    print "Arg is: #{arg}\n"
  end
end

threads.each(&:join)

puts "--"


threads = args.map do |arg|
  Thread.new(arg) do |value|
    sleep 1
    print "Arg is: #{value}\n"
  end
end

threads.each(&:join)

【讨论】:

  • 感谢您的回答,他们都按预期输出了参数。它一定是 Compass::Exec::SubCommandUI 实际上不是线程安全的。
  • 我实际上解决了我的问题,在 args 迭代循环中将 sleep 1 添加到 Thread.new 之外...
  • 我认为这不是解决您所看到的错误的正确方法。
猜你喜欢
  • 1970-01-01
  • 2020-05-03
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多