C++ 同时运行两个"processes"
C++ Having two "processes" run at the same time
在我正在构建的命令行应用程序中,我希望同时运行两个"进程"。我所说的流程,是指:
每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 执行的代码。
你也可以在这里看看如何让你的程序等待一段时间的睡眠。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在for循环中包含两个索引值的测试条件
- 在声明中合并两个常量"std::set"(不是在运行时)
- C++ 同时运行两个"processes"