带间隔的最佳无限 C++ while 循环

Optimal infinite C++ while loop with interval

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

#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。
我可以更正一些吗?

我的代码是否等同于此代码: ?

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

的 100%

假设您在 Linux 上,您可以只调用 pause(),这将挂起您的主线程,直到信号到达。

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

看来 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;
        }
    }
}