Qt线程的使用方法一20191215

代码如下:

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QMutex>

class mythread : public QThread
{
	Q_OBJECT

public:
	mythread();
	~mythread();
	//by Charles
	void closeThread();
	QMutex QMutexOperate;

protected:
	virtual void run();

private:
	//isStop是易失性变量,需要用volatile进行申明
	volatile bool isStop;
};

#endif // MYTHREAD_H
#include "mythread.h"
#include <QDebug>

mythread::mythread()
: QThread()
{
	isStop = false ;
}

mythread::~mythread()
{

}

void mythread::closeThread()
{
	/*QMutexOperate.lock();*/
	isStop = true ;
	/*QMutexOperate.unlock();*/
}

void mythread::run()
{
	while(1)
	{
		QMutexOperate.lock();
		if(isStop)
		{
			return;
		}
		QMutexOperate.unlock();
		qDebug()<<"mythread QThread::currentThreadId()=="<<QThread::currentThreadId();
		sleep(1);
	}
}

使用:

#ifndef WIDGET_H
#define WIDGET_H

#include <QtGui/QWidget>
#include "ui_widget.h"
#include "mythread.h"

class widget : public QWidget
{
	Q_OBJECT

public:
	widget(QWidget *parent = 0, Qt::WFlags flags = 0);
	~widget();

	mythread* thread1;

private:
	Ui::widgetClass ui;

	public slots:
		void onbtnOpenMyThread();
		void onbtnCloseMyThread();
		void finishedThreadBtnSlot();
};

#endif // WIDGET_H
#include "widget.h"
#include <QDebug>

widget::widget(QWidget *parent, Qt::WFlags flags)
: QWidget(parent, flags)
{
	ui.setupUi(this);
	connect(ui.OpenMyThread,SIGNAL(clicked()),this,SLOT(onbtnOpenMyThread()));
	connect(ui.CloseMyThread,SIGNAL(clicked()),this,SLOT(onbtnCloseMyThread()));
	//
	thread1 = new mythread();
	connect(thread1,SIGNAL(finished()),this,SLOT(finishedThreadBtnSlot()));
}

widget::~widget()
{
    thread1->wait();
	qDebug()<<"ConStruct~~~";
}

void widget::onbtnOpenMyThread()
{
	/*开启一个线程*/    
	thread1->start();
	qDebug()<<"Main Thread id:"<<QThread::currentThreadId();
}

void widget::onbtnCloseMyThread()
{
	/*关闭多线程*/
	thread1->closeThread();
	thread1->wait();
}

void widget::finishedThreadBtnSlot()
{
	qDebug()<<tr("finished emit");
}

结果:

Main Thread id: 0x2b44 
mythread QThread::currentThreadId()== 0x2194 
mythread QThread::currentThreadId()== 0x2194 
mythread QThread::currentThreadId()== 0x2194 
线程 'mythread' (0x2194) 已退出,返回值为 0 (0x0)。
"finished emit" 

ConStruct~~~ 

发布了140 篇原创文章 · 获赞 26 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41211961/article/details/103551571