C++中通过对子线程做超时处理

说一下我的应用场景:
在相机标定的代码中,我使用的是棋盘格标定板进行相机标定,偶然发现有时候拍摄的棋盘格图像不符合要求,通过 cv::findChessboardCorners() 这个函数进行判别,但这个API如果图像符合要求就会立刻出结果,如果不符合就会计算很久,差不多要2分钟开外。。。这就比较郁闷了,所以通过一个子线程对这个函数进行超时处理,比如如果这个函数计算时间超过1s还未出结果,则判断拍摄的棋盘格图像不合格,反之出了结果就是合格的。
基于此需求我学习了网上对于子线程做超时处理的代码,以下只是一个demo,供大家参考,也方便我以后用到时查阅。

#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <time.h>

std::mutex g_mutex_wait;                 // 互斥锁
std::condition_variable g_cond_wait;     // 条件变量

void delay(int seconds)
{
    clock_t start = clock();
    clock_t lay = (clock_t)seconds * CLOCKS_PER_SEC;
    while ((clock() - start) < lay);
}

bool testDelayAPI(bool sign) 
{
    if (sign) {
        long int num = 0;
        for (int i = 0; i < 10000000; i++) {
            num++;
        }
        g_cond_wait.notify_one();
        return true;
    }
    else {
        delay(5);
        int a = 5;
        return true;
    }
    
}

void testAPI()
{
    testDelayAPI(false);
}

int main(void)
{
	std::thread thread_input(testAPI);

    std::unique_lock<std::mutex> lockWait(g_mutex_wait);
    std::cv_status cvsts = g_cond_wait.wait_for(lockWait, std::chrono::seconds(1));

    // 消息接收超时
    if(cvsts == std::cv_status::timeout){
        std::cout << "超时!" << std::endl;
    }
    else // 接收到条件变量信号,未超时
    {
        time_t tmInputEnd = time(NULL);
        std::cout << "未超时" << std::endl;
    }
    thread_input.join();
    return 0;
}

参考:
C++线程相关的支持超时std::chrono::duration的函数总结
std::condition_variable::notify_one()伪唤醒的一个例子
std::condition_variable
C++中控制函数调用超时

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boss-dog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值