编辑:对整个帖子进行返工以涵盖基础知识。
Background.h
:
#ifndef BACKGROUND_H
#define BACKGROUND_H
#include <QThread>
#include <QObject>
class Background : public QThread
{
Q_OBJECT
public:
Background(QObject* parent = 0):QThread(parent){}
protected:
void run()
{
qDebug(qPrintable(QString("Child function ran in thread: %1").arg(QThread::currentThreadId())));
}
};
class BackgroundConcurrent : public QObject
{
Q_OBJECT
public:
BackgroundConcurrent(QObject* parent = 0):QObject(parent){}
public slots:
void doWork() const
{
qDebug(qPrintable(QString("Concurrent child function ran in thread: %1").arg(QThread::currentThreadId())));
}
};
class BackgroundTrigger : public QObject
{
Q_OBJECT
public:
BackgroundTrigger(QObject* parent = 0):QObject(parent){}
~BackgroundTrigger()
{
foreach(QObject* child, children())
{
QThread* childThread = qobject_cast<QThread*>(child);
if (childThread)
childThread->wait();
}
}
public slots:
void triggerWorker()
{
Background* child = new Background(this);
child->start();
}
};
#endif // BACKGROUND_H
main.cpp
:
#include "Background.h"
#include <QCoreApplication>
#include <QtConcurrentRun>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Using QThread
BackgroundTrigger childTrigger;
qDebug(qPrintable(QString("Main function ran in thread: %1").arg(QThread::currentThreadId())));
// Call child
childTrigger.triggerWorker();
childTrigger.triggerWorker();
// Using QtConcurrent
BackgroundConcurrent cchild;
QFuture<void> future1 = QtConcurrent::run(&cchild, &BackgroundConcurrent::doWork);
QFuture<void> future2 = QtConcurrent::run(&cchild, &BackgroundConcurrent::doWork);
return 0;
}
样本输出:
主函数在线程中运行:1087038064
子函数在线程中运行:1091267472
子函数在线程中运行:1093417872
线程中运行的并发子函数:1095519120
并发子函数在线程中运行:1097644944
确保你在你的头文件上运行 moc,qmake和cmake都支持创建你的 makefile。
这是CMakeLists.txt
我用来构建代码的文件:
cmake_minimum_required(VERSION 2.6)
#Project name
project(TEST)
#Use Qt4
find_package(Qt4)
if(QT4_FOUND)
set(QT_USE_QTOPENGL TRUE)
include(${QT_USE_FILE})
set(LIBS
${QT_LIBRARIES}
)
#Source files (*.cpp, *.o)
set(TEST_SRCS main.cpp)
#Header files (*.h[pp])
set(TEST_HDRS Background.h)
#Qt macros to handle uic, moc, etc...
QT4_WRAP_CPP(TEST_MOC ${TEST_HDRS} OPTIONS -nw)
set(TEST_ALLSRC ${TEST_SRCS} ${TEST_MOC})
#Create main
add_executable(test ${TEST_ALLSRC})
target_link_libraries(test ${LIBS})
endif(QT4_FOUND)