这个问题被弹出了好几次,但我找不到合适的答案。我想现在我找到了一个很好的解决方案!
不幸的是,parallel 不是标准发行版的一部分,但 make 是。它有一个开关-j 来做并行。
man make(1)]: (more info on make's parallel execution)
-j [jobs], --jobs[=jobs]
Specifies the number of jobs (commands) to run simultaneously. If
there is more than one -j option, the last one is effective. If
the -j option is given without an argument, make will not limit
the number of jobs that can run simultaneously.
因此,使用适当的Makefile 可以解决问题。
.PHONY: all $(PHP_DEST)
# Create an array of targets in the form of PHP1 PHP2 ... PHP90
PHP_DEST := $(addprefix PHP, $(shell seq 1 1 90))
# Default target
all: $(PHP_DEST)
# Run the proper script for each target
$(PHP_DEST):
N=$(subst PHP,,$@); php path$N/some_job_$N.php
它创建了 90 个 PHP# 目标,每个目标调用 php path#/some_job_#.php。如果您运行make -j 5,那么它将运行 5 个 php 实例并行。如果一个完成,它会开始下一个。
我将Makefile 重命名为parallel.mak,运行chmod 700 parallel.mak 并将#!/usr/bin/make -f 添加到第一行。现在可以叫./parallel.mak -j 5了。
甚至您可以使用更复杂的-l 开关:
-l [load], --load-average[=load]
Specifies that no new jobs (commands) should be started if there
are others jobs running and the load average is at least load (a
floating-point number). With no argument, removes a previous load
limit.
在这种情况下,make 将根据系统负载决定可以启动多少作业。
我用./parallel.mak -j -l 1.0 对其进行了测试并且运行良好。它起初并行启动了 4 个程序,相反 -j 没有 args 意味着尽可能多地并行运行。