Qt线程—QThread的使用--run和movetoThread的用法-@龙熙视觉李杰## 龙熙视觉

10 篇文章 1 订阅
9 篇文章 0 订阅

Qt线程—QThread的使用–run和movetoThread的用法-@龙熙视觉李杰## 龙熙视觉

Qt使用线程主要有两种方法:

方法一:继承QThread,重写run()的方法
QThread是一个非常便利的跨平台的对平台原生线程的抽象。启动一个线程是很简单的。让我们看一个简短的代码:生成一个在线程内输出"hello"并退出的线程。

  • // hellothread/hellothread.h
       class HelloThread : public QThread
       {
           Q_OBJECT
       private:
           void run();
       };
    

我们从QThread派生出一个类,并重新实现run方法。

	// hellothread/hellothread.cpp
	 void HelloThread::run()
	 {
	      qDebug() << "hello from worker thread " << thread()->currentThreadId();
	 }

run方法中包含将在另一个线程中运行的代码。在本例中,一个包含线程ID的消息被打印出来。 QThread::start()将在另一个线程中被调用。

int main(int argc, char *argv[])
 {
     QCoreApplication app(argc, argv);
     HelloThread thread;
     thread.start();
     qDebug() << "hello from GUI thread " << app.thread()->currentThreadId();
     thread.wait();  // do not exit before the thread is completed!
     return 0;
 }

另一种方法:moveToThread的方法
其实,这个方法太简单,太好用了。定义一个普通的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

其基本用法包含下面几步:

QThread *thread = new QThread;
threads *thread_slot = new threads;

//移动到另一线程
thread_slot->moveToThread(thread);
thread->start();

//两个类之间的相互通信
QObject::connect(this, SIGNAL(trans_signal()), thread_slot, SLOT(th_trans_code()));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值