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   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM