【发布时间】: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