[转] Qt 多线程学习
Qt 多线程学习
转自:http://www.cnblogs.com/IT-BOY/p/3544220.html
最近的项目上用到了关于多线程的知识,自己也比较感兴趣,所以就拿了那本《C++ GUI Qt4 编程》来学习。
这本书的第14章是关于多线程的知识,使用的Qt版本是Qt4.x。在下用的是最新的Qt 5.2,所以代码上有一些不兼容,稍加修改就可以运行了。
Qt的多线程简单来说就是继承QThread类,重载run()函数,start()启动线程。首先来看下书上的第一个例子:(修改版的代码已上传,点击下载)
class Thread : public QThread
{
Q_OBJECT
public:
Thread(QString message = "", QObject *parent = NULL);
~Thread();
void setMessage(QString);
QString getMessage(); void stop(); protected:
void run(); private:
QString message;
volatile bool stopped;
};
Thread类继承了QThread类,并实现了run函数。stopped变量前面的volatile声明stopped为易失性变量,这样每次读取stopped时都是最新的值。
继续看Thread类的实现:
Thread::Thread(QString message, QObject *parent) :
stopped(false)
, QThread(parent)
, message(message)
{
} Thread::~Thread()
{
this->stop();
this->wait();
qDebug() << this;
} void Thread::setMessage(QString message)
{
this->message = message;
} QString Thread::getMessage()
{
return this->message;
} void Thread::stop()
{
stopped = true;
} void Thread::run()
{
while (!stopped)
std::cerr << qPrintable(message);
stopped = false;
std::cerr << std::endl;
}
初始化时将stopped设置为false,run函数中持续检查stopped的值,为true时才退出。
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
QPushButton *buttonQuit = new QPushButton(QString::fromLocal8Bit("Quit"));
connect(buttonQuit, &QPushButton::clicked, this, &Dialog::close); QBoxLayout *layout = new QBoxLayout(QBoxLayout::LeftToRight, this); QStringList list = QString("ABCDEFGHIJKLMN").split("",QString::SkipEmptyParts); foreach (QString name, list)
{
Thread *thread = new Thread(name, this);
QPushButton *button = new QPushButton(QString("Start ")+name, this);
mappingTable.insert(button, thread);
connect(button, &QPushButton::clicked, this, &Dialog::startOrStopThread);
layout->addWidget(button);
} layout->addWidget(buttonQuit);
this->setLayout(layout);
} void Dialog::startOrStopThread()
{
QPushButton *buttonNow = dynamic_cast<QPushButton*>(sender());
Thread *threadNow = (Thread*)mappingTable[buttonNow]; if (threadNow == NULL) return; if(threadNow->isRunning())
{
threadNow->stop();
buttonNow->setText( buttonNow->text().replace(QString("Stop"),QString("Start")) );
}
else
{
threadNow->start();
buttonNow->setText( buttonNow->text().replace(QString("Start"),QString("Stop")) );
}
}
在Dialog界面类中,将button与thread实现一一对应的连接,在槽函数中就可以方便的找到对应的线程了。其中mappingTable是QMap<QObject*, QObject*>类型的。
这样就可以方便的实现多个线程的修改,如下图:

另外,第四个例子对我也很有启发:
TransactionThread::TransactionThread(QObject *parent) :
QThread(parent)
{
start();
} TransactionThread::~TransactionThread()
{
{
QMutexLocker locker(&mutex); while (!transactions.isEmpty())
delete transactions.dequeue(); transactionCondition.wakeOne();
} wait();
} void TransactionThread::addTransaction(Transaction *transaction)
{
QMutexLocker locker(&mutex);
transactions.enqueue(transaction);
transactionCondition.wakeOne();
} void TransactionThread::run()
{
Transaction *transaction = ;
QImage oldImage; forever
{
{
QMutexLocker locker(&mutex); if (transactions.isEmpty())
transactionCondition.wait(&mutex); if (transactions.isEmpty())
break; transaction = transactions.dequeue();
oldImage = currentImage;
} emit transactionStarted(transaction->message(), );
QImage newImage = transaction->apply(oldImage);
delete transaction; {
QMutexLocker locker(&mutex);
currentImage = newImage; if (transactions.isEmpty())
emit allTransactionsDone();
}
}
} void TransactionThread::setImage(const QImage& image)
{
QMutexLocker locker(&mutex);
currentImage = image;
} QImage TransactionThread::getImage()
{
QMutexLocker locker(&mutex);
return currentImage;
}
以上为线程实现的关键代码。在读取和写入从线程与主线程共享的变量时,都要使用mutex互斥变量。使用QMutexLocker locker(&mutex)也更方便,在构造是lock,析构时unlock,临时变量超过了作用域自然被析构,不得不说实现者的方法很巧妙啊。至于transactionCondition.wait(&mutex)则是等待条件。当事务队列为空时,等待事务加入,或者析构。加入事务时唤醒即可,即transactionCondition.wakeOne()。
[转] Qt 多线程学习的更多相关文章
- Qt 多线程学习
最近的项目上用到了关于多线程的知识,自己也比较感兴趣,所以就拿了那本<C++ GUI Qt4 编程>来学习. 这本书的第14章是关于多线程的知识,使用的Qt版本是Qt4.x.在下用的是最新 ...
- Qt多线程学习:创建多线程
[为什么要用多线程?] 传统的图形用户界面应用程序都仅仅有一个运行线程,而且一次仅仅运行一个操作.假设用户从用户界面中调用一个比較耗时的操作,当该操作正在运行时,用户界面一般会冻结而不再响应.这个问题 ...
- Qt多线程学习-用例子来理解多线程(转),这个是我看过最好的文章,总结很详细(感觉exec()的作用就是保持线程不退出,这样方便随时处理主线程发来的信号,是一种非常别致的思路)good
01 class MThread :public QThread 02 { 03 public: 04 MThread(); 05 ~MThread(); 06 virtual ...
- Qt多线程学习-用例子来理解多线程
文章出处:DIY部落(http://www.diybl.com/course/3_program/c/c_js/20090303/157373_3.html) POINT 1:QThread类的实例与 ...
- QT多线程学习
一.想要使用Qthread必须先创建,继承Qthread的类. #ifndef THREADTEST_H #define THREADTEST_H #include <QThread> # ...
- Qt 多线程和网络编程学习
一,Qt多线程类学习 QThread类,开始一个新的线程就是开始执行重新实现QThread::run(),run()是默认现实调用exec(),QThread::start()开始线程的执行,run( ...
- QT入门学习笔记2:QT例程
转至:http://blog.51cto.com/9291927/2138876 Qt开发学习教程 一.Qt开发基础学习教程 本部分博客主要根据狄泰学院唐老师的<QT实验分析教程>创作,同 ...
- 【QT】 Qt多线程的“那些事”
目录 一.前言 二.QThread源码浅析 2.1 QThread类的定义源码 2.2 QThread::start()源码 2.3 QThreadPrivate::start()源码 2.4 QTh ...
- Java多线程学习笔记
进程:正在执行中的程序,其实是应用程序在内存中运行的那片空间.(只负责空间分配) 线程:进程中的一个执行单元,负责进程汇总的程序的运行,一个进程当中至少要有一个线程. 多线程:一个进程中时可以有多个线 ...
随机推荐
- APM 终端用户体验监控分析(上)
一.前言 理解用户体验是从终端用户角度了解应用交付质量的关键,这是考量业务健康运转的潜在因素.捕获此类数据的方法各种各样,具体的实现途径由应用.基础设施架构以及管理者和管理过程决定. 二.终端用户监控 ...
- 最长连续回文串(最优线性时间O(n))
转自:http://blog.csdn.net/hopeztm/article/details/7932245 Given a string S, find the longest palindrom ...
- input:text 的value 和 attribute('value') 不是一回事
如题,input:text 当手工输入字符改变其值时,两者就不一样了. 要获得手工输入,不要用attribute('value'), 直接使用value: function getbyid(id){ ...
- GCD常用方法
1.延迟操作 2.一次性代码 3.队列组 /** * 延迟执行 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC ...
- iOS block示例
// // block.h // Block // // Created by tqh on 15/4/12. // Copyright (c) 2015年 tqh. All rights reser ...
- ***Xcode Interface Builder或Storyboard中可建立那两种连接?
在Xcode Interface Builder或Storyboard中,可建立到输出口(IBOutlet)和操作(方法,IBAction)的连接. IBOutlet are for output C ...
- Python 融于ASP框架
一.ASP的平反 想到ASP 很多人会说 “asp语言很蛋疼,不能面向对象,功能单一,很多东西实现不了” 等等诸如此类. 以上说法都是错误的,其一ASp不是一种语言是 微软用来代替CGI的一种web框 ...
- poj 2068 Nim 博弈论
思路:dp[i][j]:第i个人时还剩j个石头. 当j为0时,有必胜为1: 后继中有必败态的为必胜态!!记忆化搜索下就可以了! 代码如下: #include<iostream> #incl ...
- 搭建jenkins环境(linux操作系统)
一.虚拟机安装 1) Virtualbox安装 2) 新建镜像(将已有镜像导入) 3) 开通本地远程访问虚拟机的权限 3.1 通过本地的mac地址设置本地连接固定的ip地址.子网掩码.默认网关 ...
- poj3415 Common Substrings(后缀数组,单调栈 | 后缀自动机)
[题目链接] http://poj.org/problem?id=3415 [题意] A与B长度至少为k的公共子串个数. [思路] 基本思想是将AB各个后缀的lcp-k+1的值求和.首先将两个字符串拼 ...