• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
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 和线程

 

 

 

posted on 2017-10-11 22:27  MKT-porter  阅读(173)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3