QT的互斥量的线程同步

笔记:给定一个全局的静态变量x,利用线程来实现,每次按下start键,让它来显示1-10的数字

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QObject>
#include<QThread>
#include<QMutex>//加锁
class mythread : public QThread
{
    Q_OBJECT
public:
    explicit mythread(QObject *parent = nullptr);

signals:
protected:
    void run();
private:
    static int x;
    QMutex*mutex;
public slots:
};

#endif // MYTHREAD_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include"mythread.h"
#define MAXSIZE 2
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
public slots:
    void my_start_slot();
    void my_stop_slot();
private:
    Ui::Widget *ui;
    mythread*Mythread[MAXSIZE];
    void init();
};

#endif // WIDGET_H

main.h

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

 mythread.cpp

#include "mythread.h"
#include<QDebug>
int mythread::x=0;
mythread::mythread(QObject *parent) : QThread(parent)
{
  mutex=new QMutex;
}
void mythread::run()
{
    for(int i=0;i<10;i++)
    {
        mutex->lock();//加锁
          x++;
        qDebug()<<x<<x<<x;
        mutex->unlock();//解锁
    }
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include<QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    init();
}

Widget::~Widget()
{
    delete ui;
}
 void Widget::init()
 {
    connect(ui->btn_start,SIGNAL(clicked(bool)),this,SLOT(my_start_slot()));
    connect(ui->btn_stop,SIGNAL(clicked(bool)),this,SLOT(my_stop_slot()));
 }
void Widget::my_start_slot()
{
    for(int i=0;i<MAXSIZE;i++)
    {
         Mythread[i]=new mythread(this);
         Mythread[i]->start();
    }
    ui->btn_start->setEnabled(false);
    ui->btn_stop->setEnabled(true);
}
void Widget::my_stop_slot()
{
    for(int i=0;i<MAXSIZE;i++)
    {
         Mythread[i]->terminate();
         Mythread[i]->wait();
    }
    ui->btn_start->setEnabled(true);
    ui->btn_stop->setEnabled(false);
}

 运行结果

1 1 1

2 2 2

3 3 3

4 4 4

5 5 5

6 6 6

7 7 7

8 8 8

9 9 9

10 10 10

11 11 11

12 12 12

13 13 13

14 14 14

15 15 15

16 16 16

17 17 17

18 18 18

19 19 19

20 20 20

 说明QMutex起了作用。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值