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   

 

qt中使用C++thread

相关文章:

  • 2023-03-21
  • 2021-10-25
  • 2022-12-23
  • 2021-12-18
  • 2023-01-08
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
猜你喜欢
  • 2021-12-20
  • 2022-02-20
  • 2021-09-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案