以下是一些常见的QT多线程用法,并且包含了一些简单的代码示例:
1. QThread的基本使用
#include <QThread>
class MyThread : public QThread {
public:
void run() {
// 线程实际执行的代码
}
};
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
MyThread thread;
thread.start(); // 启动线程
// 等待线程结束
if(thread.wait(/*timeout in ms*/)) {
return 0;
} else {
return 1;
}
}
2. 信号槽机制
#include <QThread>
class MyThread : public QThread {
signals:
void progressChanged(int progress);
public:
void run() {
for(int i = 0; i < 100; i++) {
// 省略耗时操作
emit progressChanged(i);
}
}
};
class MainWindow : public QMainWindow {
public:
MainWindow() {
MyThread *thread = new MyThread(this);
connect(thread, SIGNAL(progressChanged(int)), this, SLOT(onProgressChanged(int)));
thread->start();
}
private slots:
void onProgressChanged(int progress) {
// 更新进度条等 UI 控件
}
};
3. QRunnable 和 QThreadPool 的使用
#include <QRunnable>
#include <QThreadPool>
class MyRunnable : public QRunnable {
public:
void run() {
// 线程实际执行的代码
}
};
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QThreadPool *threadPool = QThreadPool::globalInstance();
MyRunnable *runnable = new MyRunnable();
threadPool->start(runnable);
// 等待所有任务结束
threadPool->waitForDone();
return 0;
}
4. QtConcurrent::run() 的使用
#include <QtConcurrent>
void myFunction() {
// 线程实际执行的代码
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QtConcurrent::run(myFunction);
return 0;
}
这些示例只是Qt多线程用法的冰山一角。QT提供了许多不同的工具和类,可以帮助您在QT应用程序中实现高效和可扩展的多线程编程。