C++ 同时运行两个"processes"

C++ Having two "processes" run at the same time

本文关键字:两个 processes 运行 C++      更新时间:2023-10-16

在我正在构建的命令行应用程序中,我希望同时运行两个"进程"。我所说的流程,是指:

57 秒,我想做任务 A,每 250 秒做任务 B。这些是任意选择的数字,但你明白了。

如何同时检查这两个"过程"?

谢谢大家

你可以做这样的事情,如果这个过程都不需要很长时间。

float Atime = 57.f;
float Btime = 250.f;
float startTime = someTimerFunc();
while(true) {
    sleep(a few milliseconds);

    float endTime = someTimerFunc();
    float deltaTime = endTime - startTime;
    startTime = endTime;

    Atime -= deltaTime;
    Btime -= deltaTime;
    if(Atime < 0) {
        Atime += 57.f;
        AProcess();
    }
    if(Btime < 0) {
        Btime += 250.f;
        BProcess();
    }
}

或者你可以查找线程的作用。

运行 2 个线程将是处理此问题的好方法,除非您有理由需要不同的进程。像这样:

void taskA() { /*...*/ }
void taskB() { /*...*/ }
/*...*/
bool exit = false;
std::mutex mutex;
std::condition_variable cv;
auto runLoop = [&](auto duration, auto task)
    {
        std::unique_lock<std::mutex> lock{mutex};
        while(true)
        {
            if(!cv.wait_for(lock, duration, [&]{ return !exit; }))
                task();
            else
                return;
        }
    };
std::thread a{ [&]{ runLoop(std::chrono::seconds{57}, taskA); }};
std::thread b{ [&]{ runLoop(std::chrono::seconds{250}, taskB); }};

这样做是跨平台标准C++,这是一个主要的好处。它使用 C++11:lambda 和线程库。

如上所述,您可以使用线程而不是进程。如果您使用的是 c++11,请查看此处了解如何创建线程。

在链接示例中,只需将 foo 和 bar 替换为您希望任务 A 和任务 B 执行的代码。

你也可以在这里看看如何让你的程序等待一段时间的睡眠。