如何并行启动 Ruby 个命令
How to launch in Ruby commands in parallel
我正在编写一个终端程序,使用 ruby 作为一组用 C++ 和 Java 编写的程序的启动器,这些程序应该在分布式系统中执行。
我想在 ruby 中翻译这条指令:
for i in {1..40}; do
ssh node$i program & #note & so that that process is detached
done
这是我的 ruby 代码:
class Launcher
# Other method that we can ignore
def order(command)
@nodelist.each {#Do something here}
end
end
我想创建一个线程池,每个线程都执行该命令。这是合适的方法吗?正如我所研究的那样,线程无法执行 "exec" 因为线程共享相同的内存地址。
解决方法如下:
class Launcher
def initialize(commands_list)
#Expected to be an array of command string
@commands_list = commands_list
end
def execute
p_threads = @commands_list.map do |command|
Process.detach(Process.spawn(command))
end
p_threads.each(&:join)
end
end
你知道GNU parallel
吗?它是为 运行 个并行工作而设计的(惊喜!)。它由有经验的人开发,经过测试和尝试。您可能只是使用它而不是重新实现其中的大部分。或者您可以查看其手册 and/or 源代码,并从中学习。
我正在编写一个终端程序,使用 ruby 作为一组用 C++ 和 Java 编写的程序的启动器,这些程序应该在分布式系统中执行。
我想在 ruby 中翻译这条指令:
for i in {1..40}; do
ssh node$i program & #note & so that that process is detached
done
这是我的 ruby 代码:
class Launcher
# Other method that we can ignore
def order(command)
@nodelist.each {#Do something here}
end
end
我想创建一个线程池,每个线程都执行该命令。这是合适的方法吗?正如我所研究的那样,线程无法执行 "exec" 因为线程共享相同的内存地址。
解决方法如下:
class Launcher
def initialize(commands_list)
#Expected to be an array of command string
@commands_list = commands_list
end
def execute
p_threads = @commands_list.map do |command|
Process.detach(Process.spawn(command))
end
p_threads.each(&:join)
end
end
你知道GNU parallel
吗?它是为 运行 个并行工作而设计的(惊喜!)。它由有经验的人开发,经过测试和尝试。您可能只是使用它而不是重新实现其中的大部分。或者您可以查看其手册 and/or 源代码,并从中学习。