【发布时间】: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 ARGV或puts ARGV.inspect查看。我的怀疑是<arg line="..."将所有内容都塞进了一个论点,但如果没有更多信息,我不能说。 -
我试过
p ARGV和puts ARGV.inspect,它们都输出["arg1", "arg2", "arg3"]
标签: ruby multithreading sass compass-sass compass