zoukankan      html  css  js  c++  java
  • 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;
    }

    效果:

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

     效果:

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

    如果写成:

    就锁不住了。

  • 相关阅读:
    python线程同步
    闭包、装饰器
    python中的return返回值
    常用内建函数
    python迭代器与生成器
    python基础之数据类型
    VS生成解决方案时报错: Your project does not reference ".NETFramework,Version=v4.5"
    Unity 低版本打开高版本项目
    关闭应用程序的所有子窗体
    按钮接收 Enter 键
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/13278964.html
Copyright © 2011-2022 走看看