多线程编程
QThread 正确用法、跨线程信号槽与同步
#铁律:子线程不能碰 UI
这是 Qt 多线程最重要、也最容易被违反的规则:所有 QWidget 及其子类,只能在主线程(GUI 线程)创建和访问。
原因不是"Qt 规定了",而是底层现实:
- 几乎所有平台的 GUI 库(Win32、Cocoa、X11)都不是线程安全的,原生窗口句柄只能在创建它的线程操作;
- Qt 的事件循环、样式系统、字体缓存共享大量无锁保护的全局状态;
- 即便侥幸不崩,绘制结果也可能错乱、闪烁、半更新。
那么子线程要刷新界面怎么办?答案是发信号。Qt 的跨线程信号槽会自动把调用投递到目标对象所属线程的事件队列,由那个线程执行——这就是"线程间通信的官方通道"。
// ===== 文件 1:main.cpp =====
#include <QApplication>
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qDebug() << "主线程:" << QThread::currentThread();
qDebug() << "应用线程:" << app.thread();
// 判断当前是否在 GUI 线程的标准写法
const bool isGui = (QThread::currentThread() == qApp->thread());
qDebug() << "是否在 GUI 线程:" << isGui;
return 0;
}
// ===== 文件 2:遗留写法 —— 继承 QThread(不推荐)=====
#include <QThread>
class WorkerThread : public QThread
{
Q_OBJECT
protected:
void run() override
{
for (int i = 0; i < 100; ++i) {
if (isInterruptionRequested()) { // 配合 requestInterruption() 优雅退出
return;
}
msleep(50);
}
}
};每个 QObject 都记住了自己"属于"哪个线程(QObject::thread())。对象的线程归属在创建时确定,可用 moveToThread() 改变。信号槽的跨线程投递,正是依据这个归属关系决定的。
#QThread 的两种用法
上一段代码里的 WorkerThread 展示了用法一:继承 QThread。它能跑,但是个陷阱,原因见本节末尾的对比表。
#用法二:worker 对象 + moveToThread(推荐)
// ===== 文件 1:worker.h =====
#include <QObject>
#include <QAtomicBool>
#include <QThread>
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void doWork()
{
for (int i = 0; i <= 100; ++i) {
if (m_stop.loadRelaxed()) {
emit finished();
return;
}
// 模拟耗时计算
emit progress(i);
QThread::msleep(30);
}
emit finished();
}
void stop() { m_stop.storeRelaxed(true); }
signals:
void progress(int percent);
void finished();
private:
QAtomicBool m_stop{false};
};
// ===== 文件 2:mainwindow.cpp 关键片段 =====
#include <QThread>
#include <QProgressBar>
#include <QPushButton>
#include <QDebug>
void MainWindow::startWork()
{
auto *thread = new QThread(this); // 注意:QThread 对象本身属于主线程
auto *worker = new Worker; // 不能有 parent!
worker->moveToThread(thread); // 关键:改变 worker 的线程归属
connect(thread, &QThread::started,
worker, &Worker::doWork); // 线程启动后开始干活
connect(worker, &Worker::progress,
this, [this](int v) { m_bar->setValue(v); }); // 跨线程安全更新 UI
connect(worker, &Worker::finished,
thread, &QThread::quit); // 干活结束 → 退出事件循环
connect(worker, &Worker::finished,
worker, &Worker::deleteLater); // 清理 worker
connect(thread, &QThread::finished,
thread, &QThread::deleteLater); // 清理 thread
connect(thread, &QThread::finished,
this, [this]() { qDebug() << "线程已安全退出"; });
thread->start();
}
void MainWindow::stopWork()
{
// 不要在析构里直接 delete 线程对象,先通知它退出
emit requestStop(); // 或保存 worker 指针调用 worker->stop()
}#为什么 moveToThread 更好
继承 QThread 的写法混淆了两个概念:QThread 对象是"线程管理器",不是"线程本身"。
关键事实:QThread 实例的槽函数(除了 run() 里直接调用的)运行在创建它的线程,而不是它管理的新线程。所以继承 QThread 后往子类里加的槽,全都跑在主线程——这正是新手困惑的根源。
| 对比 | 继承 QThread | moveToThread + worker |
|---|---|---|
| 槽函数执行线程 | 创建它的线程(常踩坑) | 目标线程(符合直觉) |
| 能否用事件循环 | 只有 run() 里手动 exec() | 默认有 |
| 多个任务复用 | 困难 | 容易(多个对象移到同一线程) |
| 定时器/网络 | 需手动处理 | 天然支持 |
| 官方立场 | 遗留写法 | 推荐写法 |
moveToThread 模式下,QThread::run() 默认调用 exec() 开启事件循环,因此 worker 里的 QTimer、信号排队、跨线程调用全部正常工作。
那个 new Worker 后面"不能有 parent"的注释至关重要:有 parent 的对象无法 moveToThread()(Qt 会报 QObject::moveToThread: Cannot move objects with a parent)。清理靠 deleteLater 信号链。
#连接类型:Auto / Direct / Queued
connect() 的第五个参数决定信号如何投递:
| 类型 | 行为 | 场景 |
|---|---|---|
Qt::AutoConnection | 同线程→Direct,异线程→Queued(默认) | 绝大多数情况 |
Qt::DirectConnection | 立即同步调用,在发送方线程执行 | 必须立即执行且线程安全 |
Qt::QueuedConnection | 投递到接收方线程事件队列,异步 | 强制异步 |
Qt::BlockingQueuedConnection | 异步投递 + 发送方阻塞等待 | 跨线程取返回值(慎用,防死锁) |
Qt::UniqueConnection | 防止重复连接(可与上面按位或) | 避免槽被调用多次 |
#include <QObject>
#include <QThread>
#include <QDebug>
void connectionDemo(QObject *sender, QObject *receiver)
{
// 跨线程排队:receiver 的槽一定在它所属线程执行
QObject::connect(sender, &QObject::destroyed,
receiver, [] { qDebug() << "在" << QThread::currentThread() << "执行"; },
Qt::QueuedConnection);
// 强制同步:槽在发送方线程立即执行,注意线程安全
QObject::connect(sender, &QObject::objectNameChanged,
receiver, [](const QString &n) { qDebug() << n; },
Qt::DirectConnection);
}使用 QueuedConnection 有个隐含要求:参数类型必须能被 Qt 元系统识别。自定义类型要先 Q_DECLARE_METATYPE(Type) 并在连接前 qRegisterMetaType<Type>(),否则运行时报 "Cannot queue arguments of type 'X'"。
BlockingQueuedConnection 是死锁温床:如果接收方对象所在线程正阻塞等待发送方,就死锁了。绝不能在主线程用它等待子线程。
#同步原语
Qt 提供了一整套 RAII 风格的锁:
| 类 | 用途 | 特点 |
|---|---|---|
QMutex + QMutexLocker | 互斥 | 优先用 Locker,异常安全 |
QReadWriteLock + QReadLocker/QWriteLocker | 读写分离 | 读多写少时性能更好 |
QSemaphore | 计数信号量 | 限制并发数量(如连接池) |
QWaitCondition | 条件变量 | 等待某个条件成立 |
QAtomicInteger | 原子操作 | 无锁,最快 |
#include <QMutex>
#include <QMutexLocker>
#include <QReadWriteLock>
#include <QWaitCondition>
#include <QSemaphore>
#include <QQueue>
#include <QThread>
#include <QDebug>
// 1) 互斥锁:永远用 QMutexLocker,不要手动 lock/unlock
class Counter
{
public:
void inc()
{
QMutexLocker locker(&m_mutex); // 析构时自动 unlock
++m_value;
}
int value() const
{
QMutexLocker locker(&m_mutex);
return m_value;
}
private:
mutable QMutex m_mutex; // const 函数里也要能锁,故 mutable
int m_value = 0;
};
// 2) 读写锁:缓存场景,读远多于写
class Cache
{
public:
QString get(const QString &key) const
{
QReadLocker locker(&m_lock);
return m_map.value(key);
}
void put(const QString &key, const QString &val)
{
QWriteLocker locker(&m_lock);
m_map.insert(key, val);
}
private:
mutable QReadWriteLock m_lock;
QHash<QString, QString> m_map;
};
// 3) 生产者-消费者:QWaitCondition 经典范式
template <typename T>
class BlockingQueue
{
public:
void enqueue(const T &item)
{
QMutexLocker locker(&m_mutex);
m_queue.enqueue(item);
m_notEmpty.wakeOne(); // 唤醒一个等待者
}
T dequeue()
{
QMutexLocker locker(&m_mutex);
while (m_queue.isEmpty()) { // 必须用 while,不能用 if!
m_notEmpty.wait(&m_mutex); // 释放锁并等待
}
return m_queue.dequeue();
}
private:
QQueue<T> m_queue;
QMutex m_mutex;
QWaitCondition m_notEmpty;
};
// 4) 信号量:限制最多 5 个并发下载
static QSemaphore g_slots(5);
void downloadTask(const QString &url)
{
g_slots.acquire(); // 占用一个名额,满了就阻塞
qDebug() << "开始下载" << url;
QThread::msleep(1000);
g_slots.release(); // 归还名额
}wait() 循环用 while 而不是 if 是并发编程的基本功:线程被唤醒后,条件可能已被其他线程改变(虚假唤醒 / 抢占),必须重新检查。
另外一个常被忽略的点:在 const 成员函数里加锁,互斥量必须声明为 mutable,否则编译不过。
#QtConcurrent 与 QThreadPool
写 QThread 太重?如果只是"扔一段计算到后台",用 QtConcurrent:
#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>
#include <QVector>
#include <QImage>
#include <QDebug>
// 1) run:把函数扔到线程池,返回 QFuture
static int heavyCompute(int n)
{
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += i;
}
return sum;
}
void runDemo()
{
QFuture<int> f = QtConcurrent::run(heavyCompute, 1000000);
// 阻塞等待(会卡界面,仅示例)
qDebug() << "结果:" << f.result();
}
// 2) map:对容器每个元素并行处理(原地修改)
void mapDemo(QList<QImage> &images)
{
auto toGray = [](QImage &img) { img = img.convertToFormat(QImage::Format_Grayscale8); };
QFuture<void> f = QtConcurrent::map(images, toGray);
f.waitForFinished();
}
// 3) filtered:并行过滤,返回新容器
QList<int> filterDemo(const QList<int> &nums)
{
auto isEven = [](int n) { return n % 2 == 0; };
QFuture<int> f = QtConcurrent::filtered(nums, isEven);
return f.results();
}
// 4) 配合 QFutureWatcher 异步获取结果(不阻塞 UI)
void watcherDemo(QObject *parent)
{
auto *watcher = new QFutureWatcher<int>(parent);
QObject::connect(watcher, &QFutureWatcher<int>::finished, parent, [watcher, parent]() {
qDebug() << "计算完成:" << watcher->result();
watcher->deleteLater();
});
watcher->setFuture(QtConcurrent::run(heavyCompute, 500000));
}底层是全局 QThreadPool,默认最大线程数等于 CPU 核心数(QThread::idealThreadCount())。可以通过 QThreadPool::globalInstance()->setMaxThreadCount(n) 调整。
QFuture 还支持 cancel()、pause()、progressValue(),配合 QFutureWatcher 就能做出带进度和取消的后台任务。
#QRunnable:自定义池任务
需要更细的控制(比如任务要发信号、要有独立优先级)时,用 QRunnable。注意多重继承时 QObject 必须写在第一个,否则 moc 与 qobject_cast 会失效:
// ===== 文件 3:imagetask.h =====
#include <QRunnable>
#include <QThreadPool>
#include <QObject>
#include <QDebug>
class ImageTask : public QObject, public QRunnable
{
Q_OBJECT
public:
explicit ImageTask(QString path) : m_path(std::move(path))
{
setAutoDelete(true); // 跑完自动删除
}
void run() override
{
QImage img(m_path);
if (img.isNull()) {
return;
}
QImage thumb = img.scaled(128, 128, Qt::KeepAspectRatio,
Qt::SmoothTransformation);
emit done(m_path, thumb); // 跨线程信号,安全
}
signals:
void done(const QString &path, const QImage &thumb);
private:
QString m_path;
};
void submitTasks(const QStringList &paths, QObject *receiver)
{
for (const QString &p : paths) {
auto *task = new ImageTask(p);
QObject::connect(task, &ImageTask::done, receiver,
[](const QString &path, const QImage &) {
qDebug() << "缩略图完成:" << path;
});
QThreadPool::globalInstance()->start(task);
}
}
// ===== 文件 4:安全退出线程 =====
void shutdownThread(QThread *thread)
{
thread->requestInterruption(); // 1) 请求中断(设置标志位)
thread->quit(); // 2) 退出事件循环(等价于 exit(0))
if (!thread->wait(3000)) { // 3) 等待最多 3 秒
qWarning() << "线程未能在 3 秒内退出,强制终止";
thread->terminate(); // 最后手段:不安全,可能导致资源泄漏
thread->wait();
}
}#线程退出与资源清理
QThread 析构时如果线程还在跑,程序会崩溃(Qt 会报 "QThread: Destroyed while thread is still running")。上面 shutdownThread() 展示了正确的退出序列。
三步缺一不可:quit() 只让事件循环返回,如果 run() 里有阻塞的循环,必须配合 requestInterruption() 让循环退出;wait() 确保线程真的结束,之后才能安全析构。
terminate() 是危险操作——它会在任意指令处杀死线程,锁不会释放、内存不会回收、文件不会 flush。只作为最后的兜底。
完整的清理信号链是:worker finished() → worker->deleteLater() 且 worker finished() → thread->quit(),最后由 thread finished() → thread->deleteLater() 收尾。
#QTimer 的线程归属
QTimer 靠事件循环工作,因此:
QTimer对象属于哪个线程,就在哪个线程触发timeout();- 在没有
exec()的线程里,QTimer不会触发; - 跨线程
moveToThread后,定时器自动在新线程工作; timer->start()必须在其所属线程调用(或用QMetaObject::invokeMethod投递)。
#include <QThread>
#include <QTimer>
#include <QDebug>
class Poller : public QObject
{
Q_OBJECT
public:
explicit Poller(QObject *parent = nullptr) : QObject(parent)
{
m_timer.setInterval(1000);
connect(&m_timer, &QTimer::timeout,
this, &Poller::onTick);
}
void startIn(QThread *t)
{
moveToThread(t); // m_timer 是子对象,一起搬家
connect(t, &QThread::started, this, [this] { m_timer.start(); });
connect(t, &QThread::finished, this, [this] { m_timer.stop(); });
}
private slots:
void onTick()
{
qDebug() << "tick 在线程" << QThread::currentThread();
}
private:
QTimer m_timer; // 作为成员,随对象迁移
};这里 m_timer 作为 Poller 的子对象,moveToThread() 会递归移动所有子对象,因此定时器自动跟随。
#CMake 配置
find_package(Qt6 REQUIRED COMPONENTS Widgets Concurrent)
qt_add_executable(ThreadDemo main.cpp mainwindow.cpp worker.cpp)
target_link_libraries(ThreadDemo PRIVATE Qt6::Widgets Qt6::Concurrent)QtConcurrent 位于独立的 Concurrent 模块,需要单独链接。
Qt 5 提示:Qt 5 中
QThread的信号是started()/finished(),与 Qt 6 一致;差异在于 Qt 6 移除了QThread::terminate()之外的一些遗留行为,并将QtConcurrent的返回值从QFuture<T>保持了兼容。另外 Qt 5 的QTextStream编码设置方式与 Qt 6 不同,多线程日志输出时需特别注意。
#小结
- GUI 对象只能在主线程创建和访问;子线程要更新界面必须通过信号槽投递。
QThread对象是线程管理器,它的槽运行在创建它的线程——因此推荐 worker 对象 +moveToThread()模式。- 跨线程连接默认
AutoConnection,异线程时自动变QueuedConnection;自定义类型需Q_DECLARE_METATYPE+qRegisterMetaType。 - 锁一律用
QMutexLocker等 RAII 包装;QWaitCondition的等待循环必须用while。 - 线程退出三步:
requestInterruption()→quit()→wait();terminate()仅作兜底。清理靠deleteLater信号链。
#练习
- 用
moveToThread实现一个大文件 MD5 计算器:子线程分块读取并计算,主线程用QFutureWatcher显示进度百分比,支持"取消"。 - 用
QtConcurrent::mapped并行处理一个QList<QImage>(灰度化 + 缩放),对比串行与并行的耗时。 - 实现生产者-消费者模型:一个生产者线程生成随机数,
BlockingQueue缓存,两个消费者线程消费并在界面上显示各自的消费数量。 - 用
QSemaphore限制同时最多 3 个网络请求并发,写出完整代码并说明如果改成无限制会出现什么问题。