zoukankan      html  css  js  c++  java
  • QT 14 线程使用

    1 线程基础

    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;   
     }   
    

      为了启动该线程,我们的线程对象必须被初始化。start() 方法创建了一个新的线程并在新线程中调用重载的run() 方法。 在 start() 被调用后,有两个程序计数器走过程序代码。主函数启动,且仅有一个GUI线程运行,它停止时也只有一个GUI线程运行。当另一个线程仍然忙碌时退出程序是一种编程错误,因此, wait方法被调用用来阻塞调用的线程直到run()方法执行完毕。

    下面是运行代码的结果:

     hello from GUI thread  3079423696

     hello from worker thread  3076111216

    2 QObject 和线程

  • 相关阅读:
    韩式英语
    Daily dictation 听课笔记
    words with same pronunciation
    you will need to restart eclipse for the changes to take effect. would you like to restart now?
    glottal stop(britain fountain mountain)
    education 的发音
    第一次用Matlab 的lamada语句
    SVN的switch命令
    String的split
    SVN模型仓库中的资源从一个地方移动到另一个地方的办法(很久才解决)
  • 原文地址:https://www.cnblogs.com/kekeoutlook/p/7653270.html
Copyright © 2011-2022 走看看