1

如何生成多个应该异步运行的子进程?我是否使用vector子进程?恐怕下面的代码并没有做我想要完成的事情。也欢迎任何其他关于将参数传递给子进程的不同方式的建议!

#include <iostream>
#include <string>
#include <sstream>
#include "boost/process.hpp"

int main()
{
    namespace bp = boost::process;

    std::string child_process_name = "child_process";

    std::cout << "main_process: before spawning" << std::endl;

    int num_processes = 5;
    for (int i = 0; i < num_processes; ++i)
    {
        std::cout << "main_process: spawning child " << i << std::endl;
        std::stringstream ss;
        ss << i;
        std::string is;
        ss >> is;
        bp::child c(child_process_name, std::vector<std::string> {is});
        c.join();
    }

    std::cout << "main_process: waiting for children" << std::endl;

    std::cout << "main_process: finished" << std::endl;

    return 0;
}
4

2 回答 2

2

在开始下一个过程之前,您正在等待每个过程。相反,您应该将它们全部生成,然后在循环外等待它们。这是编辑后的代码:

#include <iostream>
#include <string>
#include <sstream>
#include "boost/process.hpp"

int main()
{
    namespace bp = boost::process;

    std::string child_process_name = "child_process";

    std::cout << "main_process: before spawning" << std::endl;

    constexpr int num_processes = 5;
    std::vector<bp::child> childs;
    childs.reserve(num_processes);

    for (int i = 0; i < num_processes; ++i)
    {
        std::cout << "main_process: spawning child " << i << std::endl;
        std::stringstream ss;
        ss << i;
        std::string is;
        ss >> is;
        childs.emplace_back(bp::child(child_process_name, std::vector<std::string> {is}));
    }

    std::cout << "main_process: waiting for children" << std::endl;
    
    for (auto& ch : childs)
        ch.join();
    
    std::cout << "main_process: finished" << std::endl;

    return 0;
} 
于 2020-06-26T20:36:31.367 回答
1

如何将每个进程(即 bp::child )添加到向量中。然后在一个对向量进行迭代的单独循环中,调用 join()。不要在那个循环中调用 join() ,否则事情只会按顺序运行。

于 2020-06-26T20:25:08.117 回答