笔记:给定一个全局的静态变量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起了作用。