GUI-Thread Affinity, QThread Subclassing vs Worker moveToThread()
Qt 6 widgets, backing stores, and raster surfaces omit internal locks so 60 Hz rendering never contends on mutexes; mutating a QWidget or QPixmap off the main thread corrupts heap state, while misunderstanding QThread wrapper affinity runs slots on the wrong OS thread.
What you'll learn
- Contrast overriding QThread::run() for tight blocking loops against moving an unparented worker QObject onto a QThread running exec().
- Diagnose why declaring slots directly on a QThread subclass executes those slots on the creator GUI thread instead of the worker pthread.
- Construct a deterministic worker lifecycle pairing QThread::started, requestInterruption(), QThread::finished, and QObject::deleteLater().
Why Off-Thread Widget Mutations Crash and QThread Slots Misfire
Every QObject stores a pointer to a per-thread QThreadData block captured from the OS thread that constructed it, exposed via QObject::thread(). In Qt 6.8, QWidget, QPixmap, and QPainter deliberately omit internal mutexes so 60 Hz dirty-region layout and Wayland or DRM buffer flips run lock-free. Calling label->setText() or scaling a QPixmap inside a sensor pthread races directly against the GUI thread's glyph cache and surface allocator, triggering intermittent segmentation faults under load.
Qt provides two distinct threading idioms that solve different problems. Subclassing QThread and overriding QThread::run() creates a raw OS thread without running an event loop unless you call exec(). That pattern fits tight DMA or blocking C library loops polled with isInterruptionRequested(), yet it hides a famous trap: the QThread wrapper object itself was constructed in main(), so its own thread() affinity remains the GUI thread! Any slot declared on that QThread subclass executes on the main GUI thread, freezing rendering.
Whenever background work needs timers, queued command slots, or non-blocking descriptors, keep a plain QThread (whose default run() enters exec()) and instantiate an unparented QObject worker (parent == nullptr). Pushing worker->moveToThread(&ioThread) from the creator thread rebinds worker->thread() to the spawned OS thread so every queued slot and child QTimer runs off the GUI thread.
Figure 1.1a. A QThread wrapper stays affiliated with its creator thread; moving an unparented worker QObject places slot execution inside the spawned pthread.
mental model: Picture a QThread object as the HR contract folder sitting on a plant manager's desk on the top floor (main()), while the technician hired by that contract works down on the factory floor (run()). Mailing work orders to the contract folder leaves the paperwork piled on the manager's desk; assigning tasks to the technician's workbench (worker->moveToThread()) delivers them straight to the factory floor.
Where it stops working: Unlike human staff who can carry a physical gauge upstairs, a worker thread cannot hand a QPixmap or mutate a QWidget directly; cross-thread visual data must travel as CPU-memory QImage values or POD structs.
definition (Thread Affinity (QObject::thread())): In Qt's meta-object runtime, thread affinity names the binding between each QObject and the single QThreadData event queue authorized to deliver its QTimer expirations, QSocketNotifier readiness callbacks, and Qt::QueuedConnection meta-calls. Recorded at construction time from QThread::currentThread(), affinity obeys two hard invariants: a child QObject cannot have a different affinity from its parent(), and only the currently owning thread may push an object to a new QThread.
- Step 1. Select QThread::run() overriding strictly for blocking loops without slots, and worker QObjects for event-driven I/O.
- Step 2. Allocate the worker QObject without a QWidget or controller parent so () succeeds.
- Step 3. Push affinity from the creator thread and bind QThread::finished to QObject::deleteLater for thread-local destruction.
- Step 4. Request interruption, post quit() to the worker event loop, and wait() in the controller destructor before QThread dies.
Figure 1.1b. Keep QWidget/QPixmap on main(); slots on QThread run on creator; use unparented moveToThread.
Inside QThread::run() Loops vs QObject Worker Dispatch
Under the Linux kernel 6.12 glibc runtime, QThread::start() invokes pthread_create() (entering clone3(2)) and begins executing QThreadPrivate::start(), which calls virtual QThread::run(). The base implementation of QThread::run() simply calls exec(), spinning a thread-private QEventDispatcherUNIX (epoll_wait + eventfd) until quit() or exit() posts a quit event. If you override run() with a custom while (!isInterruptionRequested()) acquisition loop and never call exec(), that thread has no running event dispatcher—so any QTimer or queued slot targeted at objects on that thread sits unread forever.
Equally critical is teardown ordering. Destroying a QThread C++ object while its underlying OS thread is still executing triggers qFatal("QThread: Destroyed while thread is still running") and calls std::terminate(). Production controllers pair requestInterruption() (for blocking run() loops) or quit() (for exec() worker loops) with a synchronous wait() inside the owning controller's destructor, while connecting &QThread::finished to worker->deleteLater() so child QTimer or descriptor members destruct on the worker thread itself before pthread exit.
Figure 1.1b. Enforcing parent==nullptr, push-only migration, and QImage value transport prevents cross-thread races and teardown aborts.
| Pattern | Event Loop (exec()) | Where Slots Execute | Engineering Use Case |
|---|---|---|---|
Subclass QThread, override run() (no exec()) | Disabled | Slots on QThread run on creator GUI thread! | Tight compute or blocking C SDK loops using isInterruptionRequested() |
moveToThread(this) inside QThread constructor | Fragile / Anti-pattern | Races QThread internal state across threads | Forbidden by Qt documentation; never write in production |
Unparented QObject + worker->moveToThread(&thr) | Active (QThread::exec()) | Slots & QTimer run cleanly on worker pthread | Primary Qt 6 pattern for buses, timers, sockets, and SQLite workers |
Off-thread QWidget / QPixmap mutation | N/A (Undefined Behavior) | Corrupts GUI backing store and compositor queues | Forbidden; build QImage in worker and convert on GUI slot |
learner@ksa:~/gl-q02/m01-l01$ bat -H 14 -H 53 qthread_vs_worker.cpp File: qthread_vs_worker.cpp #include <QImage> #include <QObject> #include <QThread> #include <QTimer> // Pattern A: QThread::run() override for a tight blocking/compute loop (no slots on this class!) class DmaComputeThread final : public QThread { Q_OBJECT signals: void blockChecksummed(quint32 seq, quint32 crc); protected: void run() override { quint32 seq = 0; while (!isInterruptionRequested()) { const quint32 crc = (++seq) ^ 0xA55AA55AU; emit blockChecksummed(seq, crc); QThread::usleep(2000); } } }; // Pattern B: Unparented QObject worker moved onto a default QThread::exec() loop class FramePrepWorker final : public QObject { Q_OBJECT public: explicit FramePrepWorker(QObject *parent = nullptr) : QObject(parent) {} public slots: void startPeriodicCapture() { Q_ASSERT(QThread::currentThread() == thread()); timer_ = new QTimer(this); // Allocated on worker_tid with worker parent connect(timer_, &QTimer::timeout, this, [this] () { QImage img(64, 64, QImage::Format_RGB888); // Safe off-thread CPU buffer img.fill(++frameSeq_ & 0xFFU); emit imagePrepared(frameSeq_, img); }); timer_->start(16); } signals: void imagePrepared(quint32 seq, const QImage &img); private: QTimer *timer_ = nullptr; quint32 frameSeq_ = 0; }; class AcquisitionRig final : public QObject { Q_OBJECT public: AcquisitionRig() { auto *worker = new FramePrepWorker(); // parent MUST be nullptr worker->moveToThread(&workerThr_); connect(&workerThr_, &QThread::started, worker, &FramePrepWorker::startPeriodicCapture); connect(&workerThr_, &QThread::finished, worker, &QObject::deleteLater); workerThr_.start(); computeThr_.start(); } ~AcquisitionRig() override { computeThr_.requestInterruption(); computeThr_.wait(); workerThr_.quit(); workerThr_.wait(); } private: DmaComputeThread computeThr_; QThread workerThr_; };- DmaComputeThread::run() declares zero slots and exits cooperatively via isInterruptionRequested() before wait().
- FramePrepWorker is created with parent==nullptr, pushed via moveToThread(&workerThr_), and cleaned up on finished->deleteLater.
QThread / QObject::moveToThread(3qt) GL-Q02 Quick Reference QThread / QObject::moveToThread(3qt) NAME QThread, QObject::moveToThread - Qt 6 OS thread management and QObject affinity transfer SYNOPSIS bool QObject::moveToThread(QThread *targetThread); void QThread::start(Priority p = InheritPriority); void QThread::requestInterruption(); void QThread::quit(); bool QThread::wait(QDeadlineTimer deadline = QDeadlineTimer(QDeadlineTimer::Forever)); INVARIANTS 1. A QThread object's own thread() is the thread that constructed the QThread wrapper. 2. moveToThread() fails and returns false if parent() != nullptr or currentThread() != thread(). 3. QWidget, QPixmap, and QPainter are restricted strictly to the main GUI thread; use QImage off-thread. ERRORS Destroying a running QThread without calling quit()/requestInterruption() + wait() calls qFatal(). Kernel Systems Academy Lesson 1.1 QThread / QObject::moveToThread(3qt) GL-Q02 quick reference · full manual page: man 3qt QThread / QObject::moveToThread Proving QThread Wrapper Affinity vs Worker Migration in Host C++20
To verify both threading patterns deterministically without requiring a Wayland display server, verify.cpp models Qt's QThreadData affinity dispatch over POSIX std::jthread queues. First, QThreadSubclassSim demonstrates the exact wrapper trap: its run() body executes on a newly spawned kernel thread (run_tid != gui_tid), yet its own QObject affinity still equals gui_tid, so dispatching a queued slot onto the QThread wrapper executes on gui_tid!
Second, QObjectSim enforces Qt's exact moveToThread() guards: rejecting migration when has_parent == true, rejecting illegal pull attempts invoked from the worker thread, succeeding when pushed from gui_tid, running the migrated worker slot on worker_tid, and flagging off-thread QPixmap/QWidget mutations while permitting QImage preparation.
learner@ksa:~/gl-q02/m01-l01$ bat -H 63 -H 91 verify.cpp File: verify.cpp #include <atomic> #include <cassert> #include <condition_variable> #include <cstdint> #include <cstdio> #include <functional> #include <mutex> #include <queue> #include <thread> class EventLoopThread { public: EventLoopThread() : thr_([this] (std::stop_token st) { loop(st); }) { std::unique_lock<std::mutex> lk(mu_); cv_.wait(lk, [this] { return started_; }); } ~EventLoopThread() { quit(); if (thr_.joinable()) thr_.join(); } void quit() { thr_.request_stop(); cv_.notify_all(); } std::thread::id spawnedTid() const { return spawned_tid_; } void post(std::function<void()> fn) { { std::lock_guard<std::mutex> lk(mu_); q_.push(std::move(fn)); } cv_.notify_one(); } private: void loop(std::stop_token st) { { std::lock_guard<std::mutex> lk(mu_); spawned_tid_ = std::this_thread::get_id(); started_ = true; } cv_.notify_all(); for (;;) { std::function<void()> fn; { std::unique_lock<std::mutex> lk(mu_); cv_.wait(lk, [&] { return !q_.empty() || st.stop_requested(); }); if (q_.empty() && st.stop_requested()) return; fn = std::move(q_.front()); q_.pop(); } fn(); } } mutable std::mutex mu_; std::condition_variable cv_; std::queue<std::function<void()>> q_; std::thread::id spawned_tid_{}; bool started_ = false; std::jthread thr_; }; struct QObjectModel { std::thread::id affinity = std::this_thread::get_id(); bool has_parent = false; bool moveToThread(std::thread::id target) { if (has_parent) return false; // Parented QObject cannot move if (std::this_thread::get_id() != affinity) return false; // Push-only from owning thread affinity = target; return true; } }; static bool canTouchWidgetOrPixmap(std::thread::id gui_tid) { return std::this_thread::get_id() == gui_tid; } int main() { const auto gui_tid = std::this_thread::get_id(); // 1. Subclassed QThread: run() executes on spawned thread, but wrapper affinity stays gui_tid! QObjectModel qthread_wrapper; // Constructed in main() -> affinity == gui_tid std::atomic<uint32_t> loop_iters{0}; std::thread::id subclass_run_tid{}; { std::jthread blocking_loop([&] (std::stop_token st) { subclass_run_tid = std::this_thread::get_id(); while (!st.stop_requested() && loop_iters.load() < 3U) { loop_iters.fetch_add(1U, std::memory_order_relaxed); } }); while (loop_iters.load() < 3U) std::this_thread::yield(); blocking_loop.request_stop(); } assert(subclass_run_tid != gui_tid); assert(qthread_wrapper.affinity == gui_tid); // Slots on QThread wrapper target gui_tid! // 2. Unparented worker QObject + moveToThread() onto EventLoopThread EventLoopThread io_thr; assert(io_thr.spawnedTid() != gui_tid); QObjectModel parented_ui_child{.has_parent = true}; assert(!parented_ui_child.moveToThread(io_thr.spawnedTid())); QObjectModel worker; std::mutex sync_mu; std::condition_variable sync_cv; bool done = false; bool illegal_pull = true; io_thr.post([&] { illegal_pull = worker.moveToThread(io_thr.spawnedTid()); std::lock_guard<std::mutex> lk(sync_mu); done = true; sync_cv.notify_one(); }); { std::unique_lock<std::mutex> lk(sync_mu); sync_cv.wait(lk, [&] { return done; }); } assert(!illegal_pull); assert(worker.moveToThread(io_thr.spawnedTid())); done = false; bool ran_on_worker = false; bool widget_blocked_off_gui = false; io_thr.post([&] { ran_on_worker = (std::this_thread::get_id() == worker.affinity); widget_blocked_off_gui = !canTouchWidgetOrPixmap(gui_tid); std::lock_guard<std::mutex> lk(sync_mu); done = true; sync_cv.notify_one(); }); { std::unique_lock<std::mutex> lk(sync_mu); sync_cv.wait(lk, [&] { return done; }); } assert(ran_on_worker && widget_blocked_off_gui && canTouchWidgetOrPixmap(gui_tid)); std::printf("AFFINITY_OK qthread_mgr_on_gui=1 run_iters=%u worker_moved=1 gui_guard=1\n", loop_iters.load()); return 0; }- moveToThread() enforces both Qt preconditions: parent==nullptr and push-only invocation from current affinity.
- Proves the QThread wrapper keeps gui_tid affinity even while its overridden run() body executes on subclass_run_tid.
Inspecting clone3 Thread Creation and Futex Synchronization
Review both the ./verify output and the strace trace. ./verify confirms qthread_mgr_on_gui=1 (proving why slots on QThread subclasses execute on main()), rejects both parented and pull-direction moveToThread() calls, executes migrated worker callbacks on io_thr, and blocks off-thread widget access. In strace, clone3() creates the OS pthreads while futex() parks and wakes the event queue cleanly with zero spin-wait CPU burn.
learner@ksa:~/gl-q02/m01-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verify -pthreadlearner@ksa:~/gl-q02/m01-l01./verifyAFFINITY_OK qthread_mgr_on_gui=1 run_iters=3 worker_moved=1 gui_guard=1learner@ksa:~/gl-q02/m01-l01learner@ksa:~/gl-q02/m01-l01strace -e \trace=clone,clone3,futex,write,exit_group ./verifyfutex(0x74edce07a7bc, FUTEX_WAKE_PRIVATE, 2147483647) = 0clone3({flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, child_tid=0x74edcd9ff990, parent_tid=0x74edcd9ff990, exit_signal=0, stack=0x74edcd1ff000, stack_size=0x7fff80, tls=0x74edcd9ff6c0} => {parent_tid=[459539]}, 88) = 459539futex(0x74edcd9ff990, FUTEX_WAIT_BITSET|FUTEX_CLOCK_REALTIME, 459539, NULL, FUTEX_BITSET_MATCH_ANY) = 0clone3({flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, child_tid=0x74edcd9ff990, parent_tid=0x74edcd9ff990, exit_signal=0, stack=0x74edcd1ff000, stack_size=0x7fff80, tls=0x74edcd9ff6c0} => {parent_tid=[459540]}, 88) = 459540futex(0x7ffc2a643600, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 0, NULL, FUTEX_BITSET_MATCH_ANY) = 0futex(0x7ffc2a6435b0, FUTEX_WAKE_PRIVATE, 1) = 0futex(0x7ffc2a643604, FUTEX_WAKE_PRIVATE, 1) = 1futex(0x7ffc2a643600, FUTEX_WAKE_PRIVATE, 1) = 1futex(0x7ffc2a643604, FUTEX_WAKE_PRIVATE, 2147483647) = 1futex(0x74edcd9ff990, FUTEX_WAIT_BITSET|FUTEX_CLOCK_REALTIME, 459540, NULL, FUTEX_BITSET_MATCH_ANY) = -1 EAGAIN (Resource temporarily unavailable)write(1, "AFFINITY_OK qthread_mgr_on_gui=1"..., 72) = 72exit_group(0) = ?+++ exited with 0 +++Thread-Affinity and QThread Lifecycle Pitfalls
Separating the QThread OS-thread controller from the QObject worker cleanly resolves 90% of Qt concurrency bugs. Use QThread::run() overrides solely for self-contained blocking or DMA compute loops with zero slots, and use unparented QObject workers moved onto default QThread instances whenever timers, signals, or I/O descriptors participate.
Allocating Child QTimers in the Worker Constructor Without Parenting:
- Symptom: Qt logs
QObject::startTimer: Timers cannot be started from another threadwhen a worker slot startspollTimer_->start(10). - Root Cause:
pollTimer_ = new QTimer()was allocated inSensorWorker::SensorWorker()onmain()withparent == nullptr, soworker->moveToThread(&ioThr)migratedworkerwhile leavingpollTimer_stranded onmain()! - Fix: Either allocate
pollTimer_ = new QTimer(this)inside a slot invoked aftermoveToThread()(&QThread::started), or passthisas the parent in the constructor so the entire child subtree moves atomically.
Destroying a Stack or Member QThread Without Calling quit() and wait():
- Symptom: Closing an HMI dialog crashes immediately with
QThread: Destroyed while thread is still running(SIGABRT). - Root Cause:
QThread ioThread_;was declared as a class member whose destructor ran before the backgroundpthreadexitedQThread::exec(). - Fix: In the owning class destructor, always call
ioThread_.requestInterruption(); ioThread_.quit(); ioThread_.wait();and wire&QThread::finishedtoworker->deleteLater().
Guided Practice
Extend verify.cpp so QObjectModel tracks a std::vector<QObjectModel *> children list. Verify that calling parent.moveToThread(io_tid) recursively updates every child's affinity atomically, whereas calling child.moveToThread(io_tid) directly returns false.
Independent Practice
Design a two-thread camera preprocessing model where a QThread::run() loop decodes raw grayscale frames into plain std::vector<uint8_t> buffers (simulating QImage), hands ownership to the main thread queue, and stops cleanly within one frame interval when requestInterruption() is asserted.
Verification Checks
Key takeaways
- Every QWidget, QPixmap, and QPainter touches unsynchronized GUI-thread backing memory, so background hardware or compute work never mutates visual objects off the main thread.
- A QThread instance is a manager QObject whose own thread() affinity belongs to the creator GUI thread, causing queued slots declared directly on a QThread subclass to run on the GUI thread.
- QObject::() transfers event-loop affinity only when parent() is nullptr and the call originates as a push from the object's current owning thread.
- Overriding QThread::run() fits dedicated blocking or compute loops checked via isInterruptionRequested(), whereas default QThread::run() calls exec() to dispatch worker QObject timers and slots.