【问题标题】:Optimal infinite C++ while loop with interval具有间隔的最佳无限 C++ while 循环
【发布时间】:2018-10-29 03:36:22
【问题描述】:

我对我的代码的正确性有疑问。
我正在制作一个作为守护进程运行的应用程序,它会在间隔内执行一些代码,代码看起来:

#include <iostream>
#include <thread>

using namespace std;

int main() {
    thread([=]() {
        while (true) {
            try {
                cout << "log" << endl;
                this_thread::sleep_for(chrono::milliseconds(3000));
            }
            catch (...) {
                cout << "Some errors here :/" << endl;
            }
        }
    }).detach();
    while (true);
}

我担心这段代码是最优的,因为在top 我可以看到,这个程序使用了大约 80% 的 CPU。
我可以更正一下吗?

我的代码是否等同于这个: https://stackoverflow.com/a/21058232/5334833?

【问题讨论】:

  • 您的主线程在 while 循环中旋转。可能你也想继续睡吧
  • 你期望while (true); 循环最后会做什么?
  • 有什么理由打电话给detach而不是join
  • 为什么要使用线程?

标签: c++ infinite-loop daemon


【解决方案1】:

while(true); 似乎是 UB。

顺便说一句,你可能会摆脱线程:

int main() {
    while (true) {
        try {
            std::cout << "log" << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(3000));
        }
        catch (...) {
            std::cout << "Some errors here :/" << std::endl;
        }
    }
}

【讨论】:

    【解决方案2】:

    while(true); 将导致您的主线程不断循环并使用 100% 的单个 CPU。

    假设您在 Linux 上,您可以直接调用 pause() 代替,这将暂停您的主线程,直到信号到达。

    由于您实际上并没有使用您的主线程,您是否有理由生成一个新线程?你能在主线程中做你的工作吗?

    【讨论】:

    • while(true); 甚至是 UB。
    猜你喜欢
    • 1970-01-01
    • 2016-08-27
    • 2015-04-29
    • 1970-01-01
    • 2013-02-22
    • 2016-04-21
    • 2021-10-15
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多