• QThread和QObject的调用方法总结


    Qt中提供了三种在主线程之外创建工作线程的方法:1. 继承QThread;2.继承QObject,然后使用moveToThread(QThread * targetThread)将对象移动到工作线程中执行;3.继承QRunnable,并将创建的对象移动到QThreadPool中进行执行。

    Qt官方建议仅仅在需要扩展QThread本身的功能时使用第一种方法,而执行一般的工作时可使用第2种或第3种方法。后两者的区别是第2种方法可以通过信号进行线程间的通信。QRunnable没有继承QObject,适合执行不关心执行进度或者不需要在中间环节进行控制的方法。

    第2种方法里面QObject和QThread的调用方法:

    ////------------------------把一个对象移动到另外的线程中之后,在其他线程调用该对象的方法需要通过信号槽的方式实现
        MyObject* myObj = new MyObject();
        QThread* thread = new QThread();
        thread->start();
        qDebug() << "current thread id : " << QThread::currentThreadId() << "  new thread : " << thread->currentThreadId();
        myObj->moveToThread(thread);
        QTimer::singleShot(0, myObj, SLOT(slotFunc()));     //会在新建线程中调用
    //    myObj->slotFunc();        //会在当前线程中调用
        QThread::currentThread()->sleep(2);     //暂停当前线程
        qDebug() << "quit thread";
        thread->quit();
        thread->deleteLater();
        myObj->slotFunc();      //线程删除之后,移动到其中的对象不会消失
    //    QThread::currentThread()->sleep(2);    //   如果退出新建线程后等待一段时间再调用obj的删除删除,会因为新建线程已经消失而不会调用
    //    QTimer::singleShot(0, myObj, SLOT(slotFunc()));     //线程消失了,该方法不会被调用
        myObj->deleteLater();   // 如果前面调用了新建线程的退出方法,该方法有一定的概率会不起作用
        qDebug() << "thread running : " << thread->isRunning();
     
  • 相关阅读:
    走出软件作坊
    [Flash入门基本动画]第8课
    [Flash入门基本动画]第6课
    数据中心十项节能妙招
    全面实施虚拟化的五个步骤
    Javascript的匿名函数
    TSQL调试器重返SQL Server 2008
    SQL Server 2008(BI)PPT下载
    通过数据中心整合和虚拟化实现高密度服务器配置
    [Flash入门基本动画]第7课
  • 原文地址:https://www.cnblogs.com/vectorli/p/4632820.html
Copyright © 2020-2023  润新知