?
序言
- 项目中需要新创建子线程并保持子线程持续运行,网上查了下,目前查到的几种方法汇总
?
方法1:while(1)/while(true)/while(flag)
?
示例1: CPU占用率100%
bool NewThread(MsgStruct* msg)
{
...
while (true) {
if (!IsSuccess()) {
continue;
}
...
}
return true;
}
- 函数中间失败/成功不能return,return后自然退出
?
示例2:使用sleep/usleep阻塞线程不至于满载
void NewThread(MsgStruct* msg)
{
...
while (1) {
usleep(10000);
}
}
?
示例3:设置特定循环条件
void NewThread(MsgStruct* msg)
{
...
bool flag = true;
while (flag) {
}
return;
}
?
示例4:线程sleep同时结合条件变量进行阻塞
void NewThread(MsgStruct* msg)
{
...
while (true) {
std::unique_lock(std::mutex) myLock(gMutex);
if (v.empty()) {
gConditionVariable.wait(myLock);
}
for (const auto& item : v) {
std::cout << item << std::endl;
}
v.clear();
gConditionVariable.notify_one();
}
}
?
方法2: while(ros::ok())
void CallBackFunction();
void NewThread()
{
ros::Rate rate(10);
while (ros::ok()) {
CallBackFunction();
rate.sleep();
}
}
?
created by shuaixio, 2022.04.28
|