1. 程式人生 > 其它 >建立一個執行緒

建立一個執行緒

技術標籤:Qtqt

//mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QObject>
#include <QDebug>
#include <QThread>

class MyThread : public QObject
{
    Q_OBJECT
private:
    int val;
    QThread m_thread;
public:
    explicit MyThread(QObject *parent = nullptr);
    void start();
    ~MyThread();

signals:

public slots:
    void doThread();
};

#endif // MYTHREAD_H
//mythread.cpp

#include "mythread.h"

MyThread::MyThread(QObject *parent) : QObject(parent)
{
    val = 10;

    connect(&m_thread, SIGNAL(started()), this, SLOT(doThread()));

    moveToThread(&m_thread);    //使當前物件的槽函式到子執行緒中執行
}

void MyThread::doThread()
{
    qDebug() << "MyThread::doThread() current thread id = " << QThread::currentThreadId();

    for(int i=0; i<10; i++)
    {
        qDebug() << "val = " << (this->val)*i;    //在解構函式中要呼叫wait()函式
        QThread::sleep(1);
    }

    qDebug() << "MyThread::doThread() end " << QThread::currentThreadId();

    m_thread.quit();
}

void MyThread::start()
{
    m_thread.start();
}

MyThread::~MyThread()
{
    m_thread.wait();    //等待子執行緒結束
}
//main.cpp

#include <QCoreApplication>
#include <mythread.h>

void test()
{
    MyThread t;
    t.start();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "main(int argc, char *argv[]) current thread id = " << QThread::currentThreadId();

    test();

    return a.exec();
}

輸出資訊