您当前的位置: 首页 >  qt

wendy_ya

暂无认证

  • 1浏览

    0关注

    342博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Qt实战案例(33)——利用QThread类实现简单多线程案例循环打印数字

wendy_ya 发布时间:2022-01-25 18:38:45 ,浏览量:1

目录
    • 一、项目介绍
    • 二、项目基本配置
    • 三、UI界面设计
    • 四、主程序实现
      • 4.1 dialog.h头文件
      • 4.2 dialog.cpp源文件
      • 4.3 workthread.h头文件
      • 4.4 workthread.cpp源文件
    • 五、效果演示

一、项目介绍

利用QThread类实现简单多线程案例循环打印数字0~9,直到单击“停止”按钮终止所有线程为止。 要创建一个线程,需要子类化QThread,并且重新实现run()函数。

二、项目基本配置

新建一个Qt案例,项目名称为“ThreadTest”,基类选择“QDialog”,取消创建UI界面复选框的选中状态,完成项目创建。然后新建一个C++ class类,类名为workthread,继承自QThread类,如下图所示: 在这里插入图片描述

三、UI界面设计

无UI界面

四、主程序实现 4.1 dialog.h头文件

定义工作线程数目:

#define MAXSIZE 1   //工作线程数目由MAXSIZE决定

声明按钮变量和相应的槽函数:

#include"workthread.h"
#define MAXSIZE 1   //工作线程数目由MAXSIZE决定
public:
    QPushButton *startBtn;
    QPushButton *stopBtn;
    QPushButton *quitBtn;

public slots :
    void slotStart();//启动线程槽函数
    void slotStop() ;//终止线程槽函数
private:
    workthread *workThread[MAXSIZE];//指向工作线程workthread的私有指针数组,记录全部线程
4.2 dialog.cpp源文件

在源文件的构造函数中,建立布局:

    //建立布局
    setWindowTitle(tr("线程")) ;
    startBtn=new QPushButton(tr ("开始"));
    stopBtn =new QPushButton(tr ("停止"));
    quitBtn =new QPushButton(tr ("退出"));
    QHBoxLayout *mainLayout = new QHBoxLayout (this) ;
    mainLayout->addWidget(startBtn);
    mainLayout->addWidget(stopBtn);
    mainLayout->addWidget(quitBtn);

布局如下: 在这里插入图片描述

按钮点击槽函数:

    connect (startBtn,SIGNAL (clicked()),this,SLOT (slotStart())) ;
    connect (stopBtn, SIGNAL (clicked()),this,SLOT(slotStop())) ;
    connect (quitBtn, SIGNAL(clicked()), this,SLOT(close()));

启动线程槽函数:

//启动线程
void Dialog::slotStart()
{
    //创建MAXSIZE个线程,并将指针保存在workThread中
    for(int i=0;isetEnabled(false);
    stopBtn->setEnabled(true);
}

停止线程槽函数:

//停止线程
void Dialog::slotStop()
{
    for(int i=0;iterminate();//终止线程
        workThread[i]->wait();//线程阻塞
    }
    startBtn->setEnabled(true);
    stopBtn->setEnabled (false);
}

【注意】:terminate()函数并不会立刻终止这个线程,该线程何时终止取决于操作系统的调度策略。因此,程序紧接着调用了QThread基类的wait()函数,它使线程阻塞等待直到退出或超时。

4.3 workthread.h头文件

声明run()函数:

protected:
    void run();
4.4 workthread.cpp源文件

定义run函数:

//不断打印数字0-9,为了显示明显,将每个数字重复打印8次
void workthread::run()
{
    while (true)
    {
        for(int n=0;n            
关注
打赏
1659256378
查看更多评论
0.0402s