参考:C++多线程类Thread(C++11)
想实现一个超时更改当前状态的功能,思路是使用子线程开一个计时器,添加标志位如果超时发送信号或者回调函数改变状态。查了很多资料,没有现成可用的,大多在主函数里调用的,故此记录,如有错误评论指正。另有关回调函数的实现博主有写另一篇博客,可以搜回调函数自行查看。
稍微写了一个demo,整体结构如下:
主函数没有什么参考意义:
// ThreadTimer.cpp : Defines the entry point for the console application.
#include <iostream>
#include <iostream>
#include <mutex>
#include "ThreadTimerClass.h"
using namespace std;
int main()
{
ThreadTimerClass a;
system("pause");
return 0;
}
实现类头文件,可以根据需求更改,这里只是核心代码没有附加任何功能:
#pragma once
#include <iostream>
#include <thread>
#include <mutex>
class ThreadTimerClass
{
public:
ThreadTimerClass();
~ThreadTimerClass();
// 超时提示
//void overTime();
bool is_timer_;
clock_t start_time_; // 开始时间
//std::mutex mt; // 如果操作了同一个变量需要加锁
// 计时器 超时提示断开相机连接
void Timer();
void start() {
std::thread TimerThread(&ThreadTimerClass::Timer, this);
TimerThread.detach();
}
};
实现类cpp:
#include "ThreadTimerClass.h"
ThreadTimerClass::ThreadTimerClass()
{
// 需要触发定时器的时候设置这两个变量
is_timer_ = true;
start_time_ = clock();
start(); // 线程开始的位置也可自定义修改
}
ThreadTimerClass::~ThreadTimerClass()
{
}
void ThreadTimerClass::Timer()
{
//mt.lock();
while (1)
{
if (is_timer_)
{
clock_t end_time = clock();
if ((double)(end_time - start_time_) / CLOCKS_PER_SEC > 3) // 超过三秒超时
{
is_timer_ = false;
std::cout << "计时结束" << std::endl;
//emit SignalOverTime(); // 是用的qt发送信号出去 可根据需求自由更改
}
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000 * 5));
}
}
}