0

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?

sal-k
  • 91
  • 8

2 Answers2

1

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;
        }
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

while(true); will cause your main thread to continuously loop and use 100% of a single CPU.

Assuming you are on Linux you can just call pause() instead which will suspend your main thread until a signal arrives.

As you aren't actually using your main thread is there a reason you are spawning a new thread at all? Can you just do your work in the main thread?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60