QT信号量QSemaphore基础学习
QSemaphore作为QT中的信号量,相当于多把互斥锁,QMutex只锁一次,而QSemaphore能锁多次,且控制多个条件。
如下:先创建一个客户类和一个线程类来使用信号量,
QSemaphore中主要函数为:
acquire(int n = 1)获取资源,默认获取第一个资源,相当于获取资源后加锁,如果没有资源会阻塞到当前位置;
available()获取当前可用资源数量;
release(int n = 1)释放n个资源,相当于开锁;
tryAcquire(int n = 1)尝试获取第n个资源,相当于开启n把锁,开锁成功后返回true,失败返回false,不阻塞。
头文件:
#include <QMainWindow>
#include <QThread>
#include <QSemaphore>
class mythread;
namespace Ui {
class mysemaphore;
}
class mysemaphore : public QMainWindow
{
Q_OBJECT
public:
explicit mysemaphore(QWidget *parent = 0);
~mysemaphore();
public slots:
void deleteSlot();
private slots:
void on_pushButton_clicked();
private:
Ui::mysemaphore *ui;
mythread* m_thread;
};
class mythread : public QThread
{
Q_OBJECT
public:
mythread();
virtual void run();
public slots:
void useSlot();
public:
QSemaphore m_semaphore;
int index;
};
cpp文件:
#include "mysemaphore.h"
#include "ui_mysemaphore.h"
#include <QDebug>
mysemaphore::mysemaphore(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::mysemaphore)
{
ui->setupUi(this);
m_thread = new mythread();
connect(ui->threadbtn,SIGNAL(clicked()),m_thread,SLOT(useSlot()));
connect(m_thread,SIGNAL(finished()),this,SLOT(deleteSlot()));
}
mysemaphore::~mysemaphore()
{
delete ui;
}
void mysemaphore::on_pushButton_clicked()
{
m_thread->start();
}
void mysemaphore::deleteSlot()
{
m_thread->wait();
m_thread->deleteLater();
}
void mysemaphore::on_lineEdit_textChanged(const QString &arg1)
{
m_thread->index = ui->lineEdit->text().toInt();
}
mythread::mythread() : m_semaphore(0),index(0)
{
}
void mythread::run()
{
while(1)
{
//获取可用资源数量
switch (index)
{
case 0:
//获取一个资源
m_semaphore.acquire();
qDebug()<<"1--unlock--sem"<<m_semaphore.available()<<"---type=0";
break;
case 1:
//获取2个资源
m_semaphore.acquire(2);
qDebug()<<"2--unlock--sem"<<m_semaphore.available()<<"---type=1";
break;
case 2:
// 尝试获取资源
if (m_semaphore.tryAcquire())
{
qDebug()<<"try--unlock--sem"<<m_semaphore.available()<<"---type=2";
}
break;
case 3:
// 尝试获取2个资源
if (m_semaphore.tryAcquire(2))
{
qDebug()<<"try--unlock-2-sem"<<m_semaphore.available()<<"---type=3";
}
break;
case 4:
// 控制多个条件
m_semaphore.acquire();
qDebug()<<"--unlock--1"<<m_semaphore.available()<<"---type=4";
m_semaphore.release();//释放1个资源
m_semaphore.acquire(2);
qDebug()<<"--unlock--2"<<m_semaphore.available()<<"---type=4";
m_semaphore.release(2);//释放2个资源
m_semaphore.acquire(3);
qDebug()<<"--unlock--3"<<m_semaphore.available()<<"---type=4";
break;
default:
qDebug()<<"no exsit"<<m_semaphore.available();
break;
}
}
}
void mythread::useSlot()
{
qDebug()<<"click--";
// 释放一个资源
m_semaphore.release();
}
结果如下: