版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyfish1986/article/details/83000763
Qt的多线程
flyfish
环境
Qt版本 5.11.2
VS2017
线程start函数会调用run函数
线程状态 isfinished() isRunning()
右键选择一个文件夹 Add Qt Class
Welcome to the Qt Class Wizard
Base class: QThread
Class Name:MyThread
Insert Q_OBJECT macro
实例1 简单的使用防止界面阻塞
MyThread.h
#pragma once
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(int num);
~MyThread();
private:
bool threadStop;
int number;
public:
void stop();
protected:
void run();
};
MyThread.cpp
#include "stdafx.h"
#include "MyThread.h"
MyThread::MyThread(int num)
{
number = num;
}
MyThread::~MyThread()
{
}
void MyThread::stop()
{
threadStop = true;
qDebug("[%d] Thread stop", number);
}
void MyThread::run()
{
threadStop = false;
int i = 0;
while (!threadStop)
{
qDebug("[%d] MyThread %d", number, i);
i++;
sleep(1);
}
}
QtGuiApplicationThread.h
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplicationThread.h"
#include "MyThread.h"
class QtGuiApplicationThread : public QMainWindow
{
Q_OBJECT
public:
QtGuiApplicationThread(QWidget *parent = Q_NULLPTR);
private:
Ui::QtGuiApplicationThreadClass ui;
public:
MyThread *thread1;
private slots:
void btn_start();
void btn_stop();
};
QtGuiApplicationThread.cpp
#include "stdafx.h"
#include "QtGuiApplicationThread.h"
QtGuiApplicationThread::QtGuiApplicationThread(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
thread1 = new MyThread(1);
connect(ui.btn_start, SIGNAL(clicked()), this, SLOT(btn_start()));
connect(ui.btn_stop, SIGNAL(clicked()), this, SLOT(btn_stop()));
}
void QtGuiApplicationThread::btn_start()
{
thread1->start();
}
void QtGuiApplicationThread::btn_stop()
{
thread1->stop();
}
实例2
生产者 生产完任务 然后通知消费者 消费
MyThread.h
#pragma once
#include <QThread>
#include <QMutex>
class Producer : public QThread
{
Q_OBJECT
public:
Producer();
~Producer();
protected:
void run();
};
class Consumer : public QThread
{
Q_OBJECT
public:
Consumer();
~Consumer();
public:
void run();
};
MyThread.cpp
#include "stdafx.h"
#include "MyThread.h"
QWaitCondition g_increase_number;
QMutex g_mutex;
int task_count = 10;
int current_pos = 0;
Producer::Producer()
{
}
Producer::~Producer()
{
}
void Producer::run()
{
g_mutex.lock();
for (int i = 0; i<task_count; i++)
{
qDebug("Producer %d", current_pos);
current_pos++;
}
g_increase_number.wakeAll();
g_mutex.unlock();
}
Consumer::Consumer()
{
}
Consumer::~Consumer()
{
}
void Consumer::run()
{
g_mutex.lock();
g_increase_number.wait(&g_mutex);
qDebug("Consumer %d", current_pos);
g_mutex.unlock();
}
调用方法
声明
public:
Producer* producer_;
Consumer *consumer_;
实现
producer_=new Producer;
consumer_=new Consumer;
producer_->start();
consumer_->start();