QT使用线程以及线程同步
2011-06-01 17:49
627 查看
首先转载一个博客,学习如何使用QT线程
http://hi.baidu.com/%D2%C0%C8%BB%BD%DA%D7%E0%C0%B6%B5%F7/blog/item/da39f4f29aa93d00b17ec522.html
QThread
似乎是很难的一个东西,特别是信号和槽,有非常多的人(尽管使用者本人往往不知道)在用不恰当(甚至错误)的方式在使用
QThread,随便用google一搜,就能搜出大量结果出来。无怪乎Qt的开发人员 Bradley T. Hughes 声嘶力竭地喊you
are-doing-it-wrong
和众多用户一样,初次看到这个时,感到 Bradley T. Hughes有
些莫名奇妙,小题大作。尽管不舒服,当时还是整理过一篇博客QThread 的使用方法
时间过去3个月,尽管依然没怎么用thread;但今天csdn论坛中有人问到这个问题,想想还是尽我所能整理一
下吧。提升自己,方便他人,何乐而不为呢?
QThread东西还是比较多的,而且我对底层对象了解有限,仅就一点进行展开(或许是大家最关心的一点):QThread
中的slots在那个线程中执行?
run
对于线程的作用相当于main函数对于应用程序。它是线程的入口,run的开始和结束意味着线程的开始和结束。
原文如下(这段话我们称为定理一
吧):
The run() implementation is for a
thread what the main() entry point is for the application. All code
executed in a call stack that starts in the run() function is executed
by the new thread, and the thread finishes when the function returns.
这么短的文字一眼就看完了,可是,这是什么意思呢?又能说明什么问题呢?看段简单代码:
对照前面的定理,run函数中的代码时确定无疑要在次线程中运行的,那么其他的呢?比如 slot
是在次线程还是主线程中运行?
你想说主线程,但又心有不甘,对么?
函数,只是这个函数大家太熟悉。我不好意思再用一堆废话来描述它,但不说又不行,那么折中一下,只看它的最后一个参数吧(为了简单起见,只看它最常用的3
个值)
下面的列表,我们暂称为定理二
:
自动连接(Auto Connection)
这是默认设置
如果发送者和接收者处于同一线程,则等同于直接连接
如果发送者和接受者位于不同线程,则等同于队列连接
也就是这说,只存在下面两种情况
直接连接(Direct Connection)
当信号发射时,槽函数将直接被调用。
无论槽函数所属对象在哪个线程,槽函数都在发射者所在线程执行。
队列连接(Queued Connection)
当控制权回到接受者所在线程的事件循环式,槽函数被调用。
槽函数在接收者所在线程执行。
同前面一样,这些文字大家都能看懂。但含义呢?
不妨继续拿前面的例子来看,slot 函数是在主线程还是次线程中执行呢?
定理二强调两个概念:发送者所在线程 和 接收者所在线程。而 slot 函数属于我们在main中创建的对象
thread,即thread属于主线程
队列连接告诉我们:槽函数在接受者所在线程执行。即 slot 将在主线程执行
直接连接告诉我们:槽函数在发送者所在线程执行。发送者在那个线程呢??不定!
自动连接告诉我们:二者不在同一线程时,等同于队列连接。即 slot 在主线程执行
太绕了?不是么(要彻底理解这几句话,你可能需要看Qt meta-object系统和Qt event系统)
怎么办
如果上两节看不懂,就记住下面的话吧(自己总结的,用词上估计会不太准确)。
QThread 是用来管理线程的,它所处的线程和它管理的线程并不是同一个东西
QThread 所处的线程,就是执行 QThread t(0) 或 QThread * t=new QThread(0)
的线程。也就是咱们这儿的主线程
QThread 管理的线程,就是 run 启动的线程。也就是次线程
因为QThread的对象在主线程中,所以他的
slot函数会在主线程中执行,而不是次线程。除非:
QThread 对象在次线程中
slot 和信号是直接连接,且信号所属对象在次线程中
但上两种解决方法都不好,因为QThread不是这么用的(Bradley T. Hughes)
好了,不在添加更多文字了,看代码,估计咱们都会轻松点
主线程
这是 Qt Manual 和 例子中普遍采用的方法。
但由于manual没说槽函数是在主线程执行的,所以不少人都认为它应该
是在次线程执行了。
定义一个 Dummy 类,用来发信号
定义一个 Thread 类,用来接收信号
重载 run 函数,目的是打印 threadid
然后看到结果(具体值每次都变,但结论不变)
看到了吧,槽函数的线程和主线程是一样的!
如果你看过Qt自带的例子,你会发现 QThread 中 slot 和 run
函数共同操作的对象,都会用QMutex锁住。为什么?
因为slot和run处于不同线程,需要线程间的同步!
如果想让槽函数slot在次线程运行(比如它执行耗时的操作,会让主线程死掉),怎么解决呢?
注意:发送dummy信号是在主线程, 接收者 thread 也在主线程中。
参考我们前面的结论,很容易想到:
将 thread 放到次线程中不就行了
这也是代码中注释掉的 moveToThread(this)所做的,去掉注释,你会发现slot在次线程中运行
这可以工作,但这是 Bradley T. Hughes 强烈批判的用法
。
推荐的方法后面会给出。
run
定义一个 Dummy 类,在run中发射它的信号
也可以在run中发射 Thread 中的信号,而不是Dummy(效果完全一样)
QThread 定义槽函数,重载run函数
想看结果么?
其实没悬念,肯定是主线程
thread 对象本身在主线程。所以它的槽也在要在主线程执行
如何解决呢?
(方法一)前面提了 moveToThread,这儿可以用,而且可以解决问题。当同样,是被批判的对象。
(方法二)注意哦,这儿我们的信号时次线程发出的,对比connect连接方式,会发现:
采用直接连接,槽函数将在次线程(信号发出的线程)执行
这个方法不太好,因为你需要处理slot和它的对象所在线程的同步。需要 QMutex 一类的东西
推荐的
千呼万唤始出来。
其实,这个方法太简单,太好用了。定义一个普通的QObject派生类,然后将其对象move到QThread
中。使用信号和槽时根本不用考虑多线程的存在。也不用使用QMutex来进行同步,Qt的事件循环会自己自动处理好这个。
结果:恩,slot确实不在主线程中运行(这么简单不值得欢呼么?)
信号与槽会与本文有点差别。比如run中使用connect时,队列连接就受限制了。其实只要理解了前面这些,没有事件循环的情况很容易就想通了。
http://doc.qt.nokia.com/4.7/threads-qobject.html
http://doc.qt.nokia.com/4.7/qthread.html
****************************************************************
上面的博客很值得细看。现在说说我做的工作。
首先是子线程的使用,就仿上面最后的例子做的。但是有几点说明:1,新建的两给类都必须是Qobject的子类。2、建立子线程那快代码必须放在主程序里,就是最后要有return exec().QT新建等待文件中,有main.cpp和mianwindows.cpp,千万不能放入后者。
当QT应用程序开始时,只有主线成是在运行的,主线成是唯一允许创建QApplication或QCoreApplication对象,并且可以对创建的对象调用exec()的线程。在调用exec()之后,这个线程等待一个事件或者处理一个时间。
下面是线程的同步。读GPS要用子线程运行,但是读出来的结果(gpsData)要和主程序共享、通信。在GPS对gpsData写入时,禁止主程序读。使用互斥量。
main.cpp中:
struct gps_data GpsData;
QMutex mutex;//互斥量保护GpsData
gps.h中:
extern struct gps_data GpsData;
extern QMutex mutex;
gps.cpp中:
mutex.lock();
GetGpsInformation(Result, &GpsData);
mutex.unlock();
graphic.h中:
extern struct gps_data GpsData;
extern QMutex mutex;
graphic.cpp中:
struct gps_data datas;
mutex.lock();
datas=GpsData;
mutex.unlock();
http://hi.baidu.com/%D2%C0%C8%BB%BD%DA%D7%E0%C0%B6%B5%F7/blog/item/da39f4f29aa93d00b17ec522.html
QThread
似乎是很难的一个东西,特别是信号和槽,有非常多的人(尽管使用者本人往往不知道)在用不恰当(甚至错误)的方式在使用
QThread,随便用google一搜,就能搜出大量结果出来。无怪乎Qt的开发人员 Bradley T. Hughes 声嘶力竭地喊you
are-doing-it-wrong
和众多用户一样,初次看到这个时,感到 Bradley T. Hughes有
些莫名奇妙,小题大作。尽管不舒服,当时还是整理过一篇博客QThread 的使用方法
时间过去3个月,尽管依然没怎么用thread;但今天csdn论坛中有人问到这个问题,想想还是尽我所能整理一
下吧。提升自己,方便他人,何乐而不为呢?
QThread东西还是比较多的,而且我对底层对象了解有限,仅就一点进行展开(或许是大家最关心的一点):QThread
中的slots在那个线程中执行?
QThread::run
run 函数是做什么用的?Manual中说的清楚:run
对于线程的作用相当于main函数对于应用程序。它是线程的入口,run的开始和结束意味着线程的开始和结束。
原文如下(这段话我们称为定理一
吧):
The run() implementation is for a
thread what the main() entry point is for the application. All code
executed in a call stack that starts in the run() function is executed
by the new thread, and the thread finishes when the function returns.
这么短的文字一眼就看完了,可是,这是什么意思呢?又能说明什么问题呢?看段简单代码:
class Thread :public QThread { Q_OBJECT public : Thread (QObject * parent =0 ):QThread (parent ){} public slots: void slot () { ... } signals: void sig (); protected : void run () { ... } }; int main (int argc , char ** argv ) { ... Thread thread ; ... }
对照前面的定理,run函数中的代码时确定无疑要在次线程中运行的,那么其他的呢?比如 slot
是在次线程还是主线程中运行?
你想说主线程,但又心有不甘,对么?
QObject::connect
涉及信号槽,我们就躲不过 connect函数,只是这个函数大家太熟悉。我不好意思再用一堆废话来描述它,但不说又不行,那么折中一下,只看它的最后一个参数吧(为了简单起见,只看它最常用的3
个值)
下面的列表,我们暂称为定理二
:
自动连接(Auto Connection)
这是默认设置
如果发送者和接收者处于同一线程,则等同于直接连接
如果发送者和接受者位于不同线程,则等同于队列连接
也就是这说,只存在下面两种情况
直接连接(Direct Connection)
当信号发射时,槽函数将直接被调用。
无论槽函数所属对象在哪个线程,槽函数都在发射者所在线程执行。
队列连接(Queued Connection)
当控制权回到接受者所在线程的事件循环式,槽函数被调用。
槽函数在接收者所在线程执行。
同前面一样,这些文字大家都能看懂。但含义呢?
不妨继续拿前面的例子来看,slot 函数是在主线程还是次线程中执行呢?
定理二强调两个概念:发送者所在线程 和 接收者所在线程。而 slot 函数属于我们在main中创建的对象
thread,即thread属于主线程
队列连接告诉我们:槽函数在接受者所在线程执行。即 slot 将在主线程执行
直接连接告诉我们:槽函数在发送者所在线程执行。发送者在那个线程呢??不定!
自动连接告诉我们:二者不在同一线程时,等同于队列连接。即 slot 在主线程执行
太绕了?不是么(要彻底理解这几句话,你可能需要看Qt meta-object系统和Qt event系统)
怎么办
呢?
如果上两节看不懂,就记住下面的话吧(自己总结的,用词上估计会不太准确)。QThread 是用来管理线程的,它所处的线程和它管理的线程并不是同一个东西
QThread 所处的线程,就是执行 QThread t(0) 或 QThread * t=new QThread(0)
的线程。也就是咱们这儿的主线程
QThread 管理的线程,就是 run 启动的线程。也就是次线程
因为QThread的对象在主线程中,所以他的
slot函数会在主线程中执行,而不是次线程。除非:
QThread 对象在次线程中
slot 和信号是直接连接,且信号所属对象在次线程中
但上两种解决方法都不好,因为QThread不是这么用的(Bradley T. Hughes)
好了,不在添加更多文字了,看代码,估计咱们都会轻松点
主线程
(信号)QThread(槽)
这是 Qt Manual 和 例子中普遍采用的方法。但由于manual没说槽函数是在主线程执行的,所以不少人都认为它应该
是在次线程执行了。
定义一个 Dummy 类,用来发信号
定义一个 Thread 类,用来接收信号
重载 run 函数,目的是打印 threadid
/*! * /file main.cpp * * Copyright (C) 2010, dbzhang800 * All rights reserved. * */ # include <QtCore / QCoreApplication> # include <QtCore / QObject> # include <QtCore / QThread> # include <QtCore / QDebug> class Dummy :public QObject { Q_OBJECT public : Dummy (){} public slots: void emitsig () { emit sig (); } signals: void sig (); }; class Thread :public QThread { Q_OBJECT public : Thread (QObject * parent =0 ):QThread (parent ) { //moveToThread(this); } public slots: void slot_main () { qDebug ()<<" from thread slot_main: " <<currentThreadId (); } protected : void run () { qDebug ()<<" thread thread: " <<currentThreadId (); exec (); } }; # include "main.moc" int main (int argc , char *argv []) { QCoreApplication a (argc , argv ); qDebug ()<<" main thread: " <<QThread ::currentThreadId (); Thread thread ; Dummy dummy ; QObject ::connect (&dummy , SIGNAL (sig ()), &thread , SLOT (slot_main ())); thread .start (); dummy .emitsig (); return a .exec (); }
然后看到结果(具体值每次都变,但结论不变)
main thread: 0x1a40 from thread slot_main: 0x1a40 thread thread: 0x1a48
看到了吧,槽函数的线程和主线程是一样的!
如果你看过Qt自带的例子,你会发现 QThread 中 slot 和 run
函数共同操作的对象,都会用QMutex锁住。为什么?
因为slot和run处于不同线程,需要线程间的同步!
如果想让槽函数slot在次线程运行(比如它执行耗时的操作,会让主线程死掉),怎么解决呢?
注意:发送dummy信号是在主线程, 接收者 thread 也在主线程中。
参考我们前面的结论,很容易想到:
将 thread 放到次线程中不就行了
这也是代码中注释掉的 moveToThread(this)所做的,去掉注释,你会发现slot在次线程中运行
main thread: 0x13c0 thread thread: 0x1de0 from thread slot_main: 0x1de0
这可以工作,但这是 Bradley T. Hughes 强烈批判的用法
。
推荐的方法后面会给出。
run
中信号与QThread中槽
定义一个 Dummy 类,在run中发射它的信号也可以在run中发射 Thread 中的信号,而不是Dummy(效果完全一样)
QThread 定义槽函数,重载run函数
/*! * /file main.cpp * * Copyright (C) 2010, dbzhang800 * All rights reserved. * */ # include <QtCore / QCoreApplication> # include <QtCore / QObject> # include <QtCore / QThread> # include <QtCore / QDebug> class Dummy :public QObject { Q_OBJECT public : Dummy (QObject * parent =0 ):QObject (parent ) {} public slots: void emitsig () { emit sig (); } signals: void sig (); }; class Thread :public QThread { Q_OBJECT public : Thread (QObject * parent =0 ):QThread (parent ) { //moveToThread(this); } public slots: void slot_thread () { qDebug ()<<" from thread slot_thread: " <<currentThreadId (); } signals: void sig (); protected : void run () { qDebug ()<<" thread thread: " <<currentThreadId (); Dummy dummy ; connect (&dummy , SIGNAL (sig ()), this , SLOT (slot_thread ())); dummy .emitsig (); exec (); } }; # include "main.moc" int main (int argc , char *argv []) { QCoreApplication a (argc , argv ); qDebug ()<<" main thread: " <<QThread ::currentThreadId (); Thread thread ; thread .start (); return a .exec (); }
想看结果么?
main thread: 0x15c0 thread thread: 0x1750 from thread slot_thread: 0x15c0
其实没悬念,肯定是主线程
thread 对象本身在主线程。所以它的槽也在要在主线程执行
如何解决呢?
(方法一)前面提了 moveToThread,这儿可以用,而且可以解决问题。当同样,是被批判的对象。
(方法二)注意哦,这儿我们的信号时次线程发出的,对比connect连接方式,会发现:
采用直接连接,槽函数将在次线程(信号发出的线程)执行
这个方法不太好,因为你需要处理slot和它的对象所在线程的同步。需要 QMutex 一类的东西
推荐的
方法
千呼万唤始出来。其实,这个方法太简单,太好用了。定义一个普通的QObject派生类,然后将其对象move到QThread
中。使用信号和槽时根本不用考虑多线程的存在。也不用使用QMutex来进行同步,Qt的事件循环会自己自动处理好这个。
/*! * /file main.cpp * * Copyright (C) 2010, dbzhang800 * All rights reserved. * */ # include <QtCore / QCoreApplication> # include <QtCore / QObject> # include <QtCore / QThread> # include <QtCore / QDebug> class Dummy :public QObject { Q_OBJECT public : Dummy (QObject * parent =0 ):QObject (parent ) {} public slots: void emitsig () { emit sig (); } signals: void sig (); }; class Object :public QObject { Q_OBJECT public : Object (){} public slots: void slot () { qDebug ()<<" from thread slot: " <<QThread ::currentThreadId (); } }; # include "main.moc" int main (int argc , char *argv []) { QCoreApplication a (argc , argv ); qDebug ()<<" main thread: " <<QThread ::currentThreadId (); QThread thread ; Object obj ; Dummy dummy ; obj .moveToThread (&thread ); QObject ::connect (&dummy , SIGNAL (sig ()), &obj , SLOT (slot ())); thread .start (); dummy .emitsig (); return a .exec (); }
结果:恩,slot确实不在主线程中运行(这么简单不值得欢呼么?)
main thread: 0x1a5c from thread slot: 0x186c
其他
本文只考虑了使用事件循环的情况,也有可能run中没有事件循环。这时信号与槽会与本文有点差别。比如run中使用connect时,队列连接就受限制了。其实只要理解了前面这些,没有事件循环的情况很容易就想通了。
参看
http://doc.qt.nokia.com/4.7/threads-starting.htmlhttp://doc.qt.nokia.com/4.7/threads-qobject.html
http://doc.qt.nokia.com/4.7/qthread.html
****************************************************************
上面的博客很值得细看。现在说说我做的工作。
首先是子线程的使用,就仿上面最后的例子做的。但是有几点说明:1,新建的两给类都必须是Qobject的子类。2、建立子线程那快代码必须放在主程序里,就是最后要有return exec().QT新建等待文件中,有main.cpp和mianwindows.cpp,千万不能放入后者。
当QT应用程序开始时,只有主线成是在运行的,主线成是唯一允许创建QApplication或QCoreApplication对象,并且可以对创建的对象调用exec()的线程。在调用exec()之后,这个线程等待一个事件或者处理一个时间。
下面是线程的同步。读GPS要用子线程运行,但是读出来的结果(gpsData)要和主程序共享、通信。在GPS对gpsData写入时,禁止主程序读。使用互斥量。
main.cpp中:
struct gps_data GpsData;
QMutex mutex;//互斥量保护GpsData
gps.h中:
extern struct gps_data GpsData;
extern QMutex mutex;
gps.cpp中:
mutex.lock();
GetGpsInformation(Result, &GpsData);
mutex.unlock();
graphic.h中:
extern struct gps_data GpsData;
extern QMutex mutex;
graphic.cpp中:
struct gps_data datas;
mutex.lock();
datas=GpsData;
mutex.unlock();
相关文章推荐
- QT使用线程以及线程同步 .
- [翻译]使用QThead进行线程开发&&线程同步
- 关于Qt在子线程中使用QMessageBox的折衷方法
- Qt:5.8新特新,QtLite使用方法,以及缩减应用体积的效果
- 如何让 Qt 的程序使用 Sleep(主线程没有Sleep函数,但线程可用自带的保护函数Sleep)
- Qt中如何使用样式表QPalette以及相关注意事项
- Qt 线程间共享数据(qRegisterMetaType的使用)
- Qt修炼手册12_线程同步与线程等待条件
- qt 线程与ui线程同步
- python使用Qt界面以及逻辑实现
- 掌握GCD以及后台永久运行的代码 (使用GCD处理后台线程和UI线程的交互)
- Qt+VC环境搭建以及使用方法
- 线程函数的设计以及MsgWaitForMultipleObjects函数的使用要点 ----- 转
- Java_基础—线程组和线程池的概述和使用以及线程的生命周期
- core dumped问题查找以及使用gdb、QT下gdbserver使用
- Qt简介以及如何配置Qt使用VS2010进行开发
- Qt简介以及如何配置Qt使用VS2010进行开发
- 使用ARM开发详细步骤/关于QT/E安装,编译,以及执行
- 线程同步(使用了synchronized)和线程通讯(使用了wait,notify)
- QT中使用另外的线程运行定时器