使 gnu - 运行 目标并行

make gnu - Run targets on parallel

我有这个 makefile,我想 运行 两个目标 并行, 自动 运行 make 而不是 make -j... 我为 make 文件中的每个 OS 使用了 makeflages 和 NPROCS (这里是达尔文) 可能吗 ?

all: module1 module2

NPROCS = $(shell sysctl hw.ncpu  | grep -o '[0-9]\+')
MAKEFLAGS += -j$(NPROCS)

.PHONY: module1
module1:
    @echo "run module 1"
    @echo $(DIR)

.PHONY: module2
module2:
    @echo "run module2”

是的,这是可能的,如果 NPROCS > 1 并且您的平台支持并行 make,您的 makefile 将执行您想要的操作。例如,参见 GNU make manual:

The MAKEFLAGS variable can also be useful if you want to have certain options, such as ‘-k’ (see Summary of Options), set each time you run make. You simply put a value for MAKEFLAGS in your environment. You can also set MAKEFLAGS in a makefile, to specify additional flags that should also be in effect for that makefile.

如果愿意,您也可以自己测试。下面证明了用 NPROCS+1 配方在并行模式下制作 运行s。每个食谱打印第一条消息,休眠 2 秒,然后打印第二条消息。

如果在并行模式下进行 运行s,您应该看到 NPROCS run moduleX with NPROCS=Y 条消息打印出来,2 秒后 NPROCS done moduleX 条消息。然后您应该看到最后一条 run moduleX with NPROCS=Y 消息,2 秒后是最后一条 done moduleX 消息。

否则,如果它不在并行模式下 运行,您将交替看到 run moduleX with NPROCS=Y 条消息和 done moduleX 条消息。

演示:

$ cat Makefile
SHELL       := bash
NPROCS      := $(shell sysctl hw.ncpu  | grep -o '[0-9]\+')
MAKEFLAGS   += -j$(NPROCS)
MODULES     := $(shell for (( i = 1; i <= $(NPROCS) + 1; i++ )); do printf 'module%d ' "$$i"; done)

.PHONY: all $(MODULES)

all: $(MODULES)

$(MODULES):
    @echo "run $@ with NPROCS=$(NPROCS)"; sleep 2; echo "done $@"

$ make
run module1 with NPROCS=8
run module2 with NPROCS=8
run module3 with NPROCS=8
run module4 with NPROCS=8
run module5 with NPROCS=8
run module6 with NPROCS=8
run module7 with NPROCS=8
run module8 with NPROCS=8
done module2
done module3
done module6
done module8
done module1
done module7
done module4
done module5
run module9 with NPROCS=8
done module9