Search code examples
c++infinite-loopdaemon

Optimal infinite C++ while loop with interval


I have a question about the correctness of my code.
I'm making a app which is run as a daemon, it do some code in interval, code looks:

#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);
}

I'm worried weather this code is optimal, because in top I can see, that this program uses about 80% of the CPU.
Can I correct something?

Is my code equivalent to this one: https://stackoverflow.com/a/21058232/5334833?


Solution

  • It appears that while(true); is UB.

    You might just get rid of thread BTW:

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