Qt之锁

mythread.h:

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QObject>
#include<QMutex>
class MyThread : public QObject
{
    Q_OBJECT
public:
    explicit MyThread(QMutex *_q,int *_x,QObject *parent = nullptr);
signals:
public slots:
    void working();
private:
    int * x;
    QMutex *q;
};

#endif // MYTHREAD_H

mythread.cpp:

#include "mythread.h"
#include<QDebug>
#include<QMutex>
MyThread::MyThread(QMutex *_q,int* _x,QObject *parent)
    : QObject(parent),x(_x),q(_q)
{

}
void  MyThread::working()
{
   qDebug()<<"线程启动了"<<"object_name"<<this->objectName()<<endl;
   for(int i=0;i<500000;i++)
   {
       q->lock();
       int temp=*x;
       temp++;
       *x=temp;
      q->unlock();
   }
    qDebug()<<"线程结束了"<< "x="<<*x<<"object_name"<<this->objectName()<<endl;
}

widget.h:

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include"mythread.h"
#include<QThread>
class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QMutex *mutex=0,int _value=0,QWidget *parent = 0);
    ~Widget();
private:
    int value;
    MyThread *t1;
    MyThread *t2;
    QThread *w1;
    QThread *w2;
    QMutex *mutex;
};

#endif // WIDGET_H

widget.cpp:

#include "widget.h"
#include "mythread.h"
Widget::Widget(QMutex *mutex,int _value,QWidget *parent)
    : QWidget(parent),value(_value)
{
    mutex=new QMutex;
    t1=new MyThread(mutex,&value);
    t2=new MyThread(mutex,&value);
    w1=new QThread(this);
    w2=new QThread(this);
    t1->setObjectName("t1");
    t2->setObjectName("t2");
    t1->moveToThread(w1);
    t2->moveToThread(w2);

    connect(w1,SIGNAL(started()),t1,SLOT(working()));
    connect(w2,SIGNAL(started()),t2,SLOT(working()));
    connect(w1,SIGNAL(finished()),t1,SLOT(deleteLater()));
    connect(w2,SIGNAL(finished()),t2,SLOT(deleteLater()));
    w1->start();
    w2->start();
}

Widget::~Widget()
{
   w1->quit();
   w1->wait();
   w2->quit();
   w2->wait();
   delete  mutex;
}

效果:

 

 

其中这所可以找个托管的:

 

 效果:

 

 

智能锁一般应用于比较短的函数:

 

 

如果写成:

 

就锁不住了。

 

posted @ 2020-07-10 14:15  sunshine_gzw  阅读(1392)  评论(0编辑  收藏  举报