并行调用 C++ 和 运行 中的可执行文件

call executables in c++ and run in parallel

在 C++ 中,我使用 system("./filename blahblah"); 调用可执行文件现在因为有很多迭代我想把它们并行

#pragma omp parallel for
for( int i = 0; i < 999; ++i )
system("./filename blahblah");

但我很确定上面的方法行不通,因为#pragma omp 是 C++ 编译器的扩展,只能修改 C++ 行的编译。 system() 调用终端 shell 来处理命令,#pragma omp 不会影响该命令的执行。

有没有办法解决这个问题?我确实认为 GNU 中有一种使用 fork() 和 exec() 的方法,但我不知道具体如何。谁能帮我这个?谢谢。

是的,您需要使用 fork(2), execve(2), waitpid(2), pipe(2) and some other syscalls(2) (e.g. poll(2) is useful for an event loop,您可能还需要一个) 等等...

我不会解释如何操作,请阅读 Advanced Linux Programming 一本书(可在线获取),其中有几章专门讨论该主题(其中大部分与其他 POSIX 系统相关,例如 MaCOSX ).

您可能对 MPI 感兴趣。

顺便说一句,拥有一千个 运行 进程在大多数计算机上是不合理的。您最好将自己限制在最多十几个 运行 个进程(例如,有一些 pool 个进程)。 您通常希望每个 core (and slightly more if you have an hyper-threaded Intel processor). If you have too many running processes, your system would be unresponsive and the overall performance would suffer (the scheduler 不超过一个 运行 个进程或线程(即任务)将有太多活动任务需要管理。

您可能对 batch systems (e.g. you could popen(3) a batch command; on MacOSX see also launchd) 感兴趣。