qt中使用C++thread

win.h

#ifndef WIN_H
#define WIN_H

#include <QWidget>
#include <thread>
#include <chrono>
#include <QDebug>




class Win : public QWidget
{
    Q_OBJECT

public:
    Win(QWidget *parent = nullptr);
    ~Win();
private:
    void hello();  //线程要调用的函数
    std::thread* t;
    //注意:这个变量不要在构造函数中定义成局部变量,否则构造函数结束,线程对象就释放了

};
#endif // WIN_H

win.cpp

#include "win.h"

Win::Win(QWidget *parent)
    : QWidget(parent)
{
    this->resize(400,300);
     t=new std::thread(&Win::hello,this);  //创建线程并启动
     //t  线程名
     //参数1:线程要执行的函数地址

}

Win::~Win()
{
}

void Win::hello()
{
    for (int i = 0; i < 30; i++) {
            qDebug() << "子线程:" << i;
            std::this_thread::sleep_for(std::chrono::seconds(2));  //本线程休眠2秒
        }
}

工程下载地址:链接:https://pan.baidu.com/s/18CQTU_i8WcJfif1CoUQmRA 提取码:6666   

 

posted @ 2020-11-01 21:39  天子骄龙  阅读(907)  评论(0)    收藏  举报