前言:
场景:
应用启动时候启动一个线程,线程里面隔几秒查询一个设备的状态。在关闭该软件的时候唤醒线程一起关闭。于是想到使用条件变量来做该逻辑。如下:
struct timespec abstime;
struct timeval now;
long timeout_ms = 100; // wait time 100ms
gettimeofday(&now, NULL);
long nsec = now.tv_usec * 1000 + (timeout_ms % 1000) * 1000000;
abstime.tv_sec=now.tv_sec + nsec / 1000000000 + timeout_ms / 1000;
abstime.tv_nsec=nsec % 1000000000;
pthread_cond_timedwait(&cond, &mutex, &abstime);
函数pthread_cond_timedwait可以设置等待超时。刚好满足我们的需求。
具体使用如下:
Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Cond;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void startThread();
private slots:
void on_btnStart_clicked();
private:
Ui::Widget *ui;
Cond *mCond;
};
#endif // WIDGET_H
Widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "cond.h"
#include <QtConcurrent>
#include <QDebug>
#include <QTimer>
#include <QEventLoop>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
mCond = new Cond();
}
Widget::~Widget()
{
delete ui;
mCond->Signal();
}
void Widget::startThread()
{
QtConcurrent::run(QThreadPool::globalInstance(), [=](){
do{
mCond->Lock();
if ( 0 == mCond->TimedWait(1) )
break;
qDebug()<<" thread id : "<<QThread::currentThreadId();
mCond->Unlock();
}while(1);
});
}
void Widget::on_btnStart_clicked()
{
startThread();
}
测试代码链接: