Cross-Thread AutoConnection, QMetaCallEvent & BlockingQueued Deadlocks

Qt::AutoConnection decides between a synchronous C++ stack call and a heap-allocated QMetaCallEvent dynamically at each emit—and misusing Qt::BlockingQueuedConnection across symmetric or same-thread paths freezes the entire HMI inside an unrecoverable futex wait.

30 minfree previewLinux 6.12→ module 1 lab
What you'll learn
  • Trace QMetaObject::activate() dispatch across DirectConnection, QueuedConnection, and AutoConnection when receiver affinity changes.
  • Register custom C++20 value structs with Q_DECLARE_METATYPE and qRegisterMetaType for safe QMetaCallEvent heap copying.
  • Eliminate same-thread and symmetric two-thread BlockingQueuedConnection deadlocks using asynchronous signals and QReadWriteLock.

How QMetaObject::activate() Crosses Thread Boundaries

When you connect two QObject instances with default Qt::AutoConnection, Qt does not hard-wire same-thread or cross-thread delivery during connect(). Instead, every emit enters QMetaObject::activate() and compares QThread::currentThread() with receiver->thread() at that exact instant. If both match, Qt invokes the slot directly on the emitter's call stack (Qt::DirectConnection) with zero heap allocation. If they differ, Qt allocates a QMetaCallEvent, copy-constructs every argument via QMetaType, locks the receiver thread's QPostEventList, enqueues the event, and pokes its eventfd wakeup descriptor.

Two immediate consequences govern C++20 argument types. First, custom structs crossing a Qt::QueuedConnection must be copy-constructible value types declared with Q_DECLARE_METATYPE(MyStruct) (and qRegisterMetaType<MyStruct>() when queued by string name or dynamic meta-calls). Passing const uint8_t * pointing to a stack buffer on the emitter thread is fatal Undefined Behavior because the emitter stack frame unwinds long before the GUI event loop dequeues the QMetaCallEvent.

Second, Qt::BlockingQueuedConnection posts the same QMetaCallEvent and then blocks the emitting thread on an internal QSemaphore (futex) until the receiver slot finishes. If currentThread() == receiver->thread(), the thread blocks waiting for itself to pump events—instant deadlock! Worse, if the GUI blocks on a worker via BlockingQueuedConnection at the same moment the worker emits a BlockingQueuedConnection back to the GUI, both threads sleep forever in a two-node wait cycle.

fig_m01_l02_a.svg — Qt::AutoConnection checks receiver->thread() on every…

Figure 1.2a. Qt::AutoConnection checks receiver->thread() on every emit; symmetric or self-targeted waits deadlock immediately.

mental model: Think of DirectConnection as speaking to a teammate standing beside you, QueuedConnection as dropping a photocopied work sheet into another department's mail slot, and BlockingQueuedConnection as bolting your office door shut from the inside and refusing to open it until that other department signs and returns your sheet.

Where it stops working: If both departments bolt their doors simultaneously while waiting for each other's signature—or you mail a sheet to your own bolted office—no human supervisor breaks the lock: Linux kernel FUTEX_WAIT sleeps indefinitely.

definition (QMetaCallEvent and QMetaType Value Marshaling): QMetaCallEvent is Qt's internal QEvent subclass (QEvent::MetaCall) that packages a target slot index together with heap-allocated copies of every signal argument for cross-thread delivery. QMetaType supplies the type-erased copy-constructor and destructor table generated by Q_DECLARE_METATYPE and registered at runtime with qRegisterMetaType<T>(), allowing the receiver thread's event loop to unpack, invoke, and destroy the copied arguments safely after the sender's stack frame has already returned.

ast_m01_l02.svg — AutoConnection checks thread() per emit; copy value…step 1/4
  1. Step 1. Package cross-thread payloads as self-contained value structs with zero raw pointers into caller stack memory.
  2. Step 2. Declare Q_DECLARE_METATYPE in the header and call qRegisterMetaType at startup so queued argument copying always resolves.
  3. Step 3. Use default Qt::AutoConnection or explicit Qt:: so neither thread blocks waiting on the peer's event loop.
  4. Step 4. Replace synchronous cross-thread getter signals with a small QReadWriteLock-protected state object.

Figure 1.2b. AutoConnection checks thread() per emit; copy value structs via QueuedConnection, never cycle.

Memory Lifetime Across Queued Meta-Calls and Lock Ordering

Inspect what happens in memory during a cross-thread Qt::DirectConnection mistake. Forcing Qt::DirectConnection between a background worker and a QWidget slot bypasses QPostEventList entirely and executes MainWindow::onSample() on the worker pthread! The code compiles cleanly without warnings, yet mutates widget members concurrently with paintEvent(). Always treat explicit Qt::DirectConnection across threads as a low-level hook permitted only when the slot itself touches solely atomic or mutex-guarded non-GUI data.

Notice also why connect() order relative to moveToThread() is harmless under Qt::AutoConnection: because AutoConnection checks receiver->thread() at emit time, calling connect(ctrl, &Ctrl::cmd, worker, &Worker::onCmd) before worker->moveToThread(&thr) still dispatches via QueuedConnection once thr is running. By contrast, if a subsystem ever uses BlockingQueuedConnection, impose a strict directed acyclic hierarchy (for example, shutdown supervisor -> leaf worker only, never leaf -> GUI) and assert QThread::currentThread() != receiver->thread() beforehand.

fig_m01_l02_b.svg — Copying registered value structs into QMetaCallEvent…

Figure 1.2b. Copying registered value structs into QMetaCallEvent decouples emitter stack lifetime from asynchronous GUI consumption.

Connection TypeExecution ThreadArgument Lifetime RuleDeadlock / Race Risk
Qt::AutoConnection (default)receiver->thread() (checked per emit)Copied via QMetaType whenever cross-threadSafe default for 99% of QObject connections
Qt::DirectConnectionAlways emitter's OS threadBorrowed stack references valid during callData race if receiver is a QWidget or unguarded QObject
Qt::QueuedConnectionAlways receiver->thread() asynchronouslyMust be registered copyable value (qRegisterMetaType)Zero deadlock risk; floods queue only above ~1 kHz
Qt::BlockingQueuedConnectionreceiver->thread(), emitter parked on semaphoreReferences stay alive until slot returnsInstant deadlock on same-thread or A <-> B wait cycles
learner@ksa: ~/gl-q02/m01-l02
learner@ksa:~/gl-q02/m01-l02$ bat -H 11 -H 16 queued_metacall_guard.cpp File: queued_metacall_guard.cpp    #include <QMetaType>    #include <QObject>    #include <QReadWriteLock>    #include <QThread>        struct TelemetryFrame {      quint64 mono_ns = 0;      qint32 scaled_uv = 0;      quint32 flags = 0;    };  Q_DECLARE_METATYPE(TelemetryFrame)        class SharedCalibration {    public:      qint32 scale(qint32 raw_uv) const {      QReadLocker rd(&lock_);        return static_cast<qint32>((qint64{raw_uv} * gain_permille_) / 1000 + offset_uv_);      }      void setCoefficients(qint32 gain_permille, qint32 offset_uv) {        QWriteLocker wr(&lock_);        gain_permille_ = gain_permille;        offset_uv_ = offset_uv;      }        private:      mutable QReadWriteLock lock_;      qint32 gain_permille_ = 1000;      qint32 offset_uv_ = 0;    };        class AcquisitionWorker final : public QObject {      Q_OBJECT    public:      explicit AcquisitionWorker(const SharedCalibration *cal, QObject *parent = nullptr)          : QObject(parent), cal_(cal) {        qRegisterMetaType<TelemetryFrame>("TelemetryFrame");      }        public slots:      void processAdcSample(quint64 mono_ns, qint32 raw_uv) {        TelemetryFrame frame{mono_ns, cal_->scale(raw_uv), 0x01U};        emit framePublished(frame); // AutoConnection -> QueuedConnection to GUI      }        signals:      void framePublished(const TelemetryFrame &frame);        private:      const SharedCalibration *cal_;    };
  1. Q_DECLARE_METATYPE plus qRegisterMetaType registers TelemetryFrame copy/destroy hooks for heap QMetaCallEvent packing.
  2. QReadLocker lets the worker scale samples concurrently while rare GUI calibration edits acquire QWriteLocker.
Qt::ConnectionType / qRegisterMetaType(3qt) at a glance — GL-Q02
Qt::ConnectionType / qRegisterMetaType(3qt) GL-Q02 Quick Reference Qt::ConnectionType / qRegisterMetaType(3qt) NAME       QObject::connect, Qt::ConnectionType, qRegisterMetaType - cross-thread       signal delivery SYNOPSIS       int qRegisterMetaType<T>(const char *typeName = nullptr);       QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal,                                             const QObject *receiver, PointerToMemberFunction method,                                             Qt::ConnectionType type = Qt::AutoConnection); INVARIANTS       1. AutoConnection evaluates QThread::currentThread() ==       receiver->thread() on every emit. 2. QueuedConnection allocates a       QMetaCallEvent and copy-constructs all registered value arguments. 3.       BlockingQueuedConnection MUST NEVER be emitted when currentThread() ==       receiver->thread() or when receiver's thread may symmetrically block       waiting on sender's thread. ERRORS       Unregistered custom types on dynamic queued connections log 'Cannot       queue arguments of type T' and drop. Kernel Systems Academy Lesson 1.2  Qt::ConnectionType / qRegisterMetaType(3qt) GL-Q02 quick reference · full manual page: man 3qt Qt::ConnectionType / qRegisterMetaType 

Verifying AutoConnection Dispatch, MetaType Copies & Cycle Detection

Our host C++20 verification harness verify.cpp tests all four runtime contracts of Lesson 1.2. First, MetaTypeRegistry verifies that unregistered custom payload types fail queued marshaling cleanly until registered, and proves deep value isolation by zeroing the worker's local stack struct immediately after emission before the main thread runs the queued event.

Second, WaitForGraph verifies that both same-thread BlockingQueuedConnection (T1 -> T1) and symmetric cross-thread BlockingQueuedConnection (GUI -> Worker while Worker -> GUI) are caught deterministically as wait-for cycles, while std::shared_mutex + AutoConnection delivers calibrated frames cleanly onto main_tid.

learner@ksa: ~/gl-q02/m01-l02
learner@ksa:~/gl-q02/m01-l02$ bat -H 27 -H 91 verify.cpp File: verify.cpp    #include <cassert>    #include <condition_variable>    #include <cstdint>    #include <cstdio>    #include <cstring>    #include <functional>    #include <mutex>    #include <queue>    #include <shared_mutex>    #include <thread>    #include <unordered_map>    #include <unordered_set>        struct TelemetryFrame {      uint64_t mono_ns;      int32_t scaled_uv;      uint32_t flags;    };        class MetaTypeRegistry {    public:      void registerType(const char *name) { known_.insert(name); }      bool isRegistered(const char *name) const { return known_.count(name) != 0; }    private:      std::unordered_set<std::string> known_;    };      class WaitForGraph {    public:      bool enterBlockingQueued(int emitter_tid, int receiver_tid) {        std::lock_guard<std::mutex> lk(mu_);        if (emitter_tid == receiver_tid) return false; // Instant self-deadlock!        int cur = receiver_tid;        while (edges_.count(cur)) {          cur = edges_[cur];          if (cur == emitter_tid) return false; // Symmetric wait-for cycle!        }        edges_[emitter_tid] = receiver_tid;        return true;      }      void leaveBlockingQueued(int emitter_tid) {        std::lock_guard<std::mutex> lk(mu_);        edges_.erase(emitter_tid);      }    private:      std::mutex mu_;      std::unordered_map<int, int> edges_;    };        struct CalStore {      mutable std::shared_mutex rw;      int32_t gain_permille = 1000;      int32_t offset_uv = 0;      int32_t scale(int32_t raw) const {        std::shared_lock<std::shared_mutex> rd(rw);        return static_cast<int32_t>((int64_t{raw} * gain_permille) / 1000 + offset_uv);      }      void update(int32_t g, int32_t o) {        std::unique_lock<std::shared_mutex> wr(rw);        gain_permille = g;        offset_uv = o;      }    };        int main() {      WaitForGraph wg;      assert(!wg.enterBlockingQueued(1, 1));  // Same-thread BlockingQueued deadlock      assert(wg.enterBlockingQueued(1, 2));   // GUI(1) blocks on Worker(2)      assert(!wg.enterBlockingQueued(2, 1));  // Worker(2) -> GUI(1) symmetric deadlock!      wg.leaveBlockingQueued(1);          MetaTypeRegistry reg;      assert(!reg.isRegistered("TelemetryFrame"));      reg.registerType("TelemetryFrame");      assert(reg.isRegistered("TelemetryFrame"));          CalStore cal;      cal.update(1025, -50); // 4000 * 1.025 - 50 = 4050          const auto main_tid = std::this_thread::get_id();      std::mutex q_mu;      std::condition_variable q_cv;      std::queue<std::function<void()>> gui_ev_q;      std::thread::id executed_tid{};      TelemetryFrame delivered{};      int direct_calls = 0;      int queued_calls = 0;          auto emit_auto = [&] (std::thread::id rx_tid, const TelemetryFrame &arg) -> bool {        if (std::this_thread::get_id() == rx_tid) {        ++direct_calls;          executed_tid = std::this_thread::get_id();          delivered = arg;          return true;        }        if (!reg.isRegistered("TelemetryFrame")) return false;        TelemetryFrame heap_copy = arg; // QMetaCallEvent value copy        {          std::lock_guard<std::mutex> lk(q_mu);          ++queued_calls;          gui_ev_q.push([&, heap_copy] {            executed_tid = std::this_thread::get_id();            delivered = heap_copy;          });        }        q_cv.notify_one();        return true;      };          // Same-thread AutoConnection -> Direct call on stack      TelemetryFrame local_f{100ULL, 500, 1U};      assert(emit_auto(main_tid, local_f));      assert(direct_calls == 1 && queued_calls == 0 && executed_tid == main_tid);          // Cross-thread AutoConnection -> Queued copy survives sender stack wipe      {        std::jthread worker([&] {          TelemetryFrame stack_frame{200ULL, cal.scale(4000), 3U};          assert(emit_auto(main_tid, stack_frame));          std::memset(&stack_frame, 0, sizeof(stack_frame)); // Wipe sender stack!        });      }      {        std::unique_lock<std::mutex> lk(q_mu);        q_cv.wait(lk, [&] { return !gui_ev_q.empty(); });        auto ev = std::move(gui_ev_q.front());        gui_ev_q.pop();        lk.unlock();        ev();      }      assert(queued_calls == 1 && executed_tid == main_tid);      assert(delivered.mono_ns == 200ULL && delivered.scaled_uv == 4050 && delivered.flags == 3U);          std::printf("METACALL_OK direct=%d queued=%d cycle_caught=1 scaled_uv=%d\n",                  direct_calls, queued_calls, delivered.scaled_uv);      return 0;    }
  1. WaitForGraph catches both self-edges (emitter==receiver) and multi-hop BlockingQueued wait cycles.
  2. QMetaCallEvent value copy preserves TelemetryFrame fields even after memset wipes the worker's stack frame.

Confirming Copy Isolation and Deadlock Rejection

Check the execution capture: METACALL_OK direct=1 queued=1 cycle_caught=1 scaled_uv=4050 proves that same-thread AutoConnection executes directly on main_tid, cross-thread emission copies TelemetryFrame safely before the worker zeroes its stack frame and exits, and WaitForGraph blocks both same-thread and 1 <-> 2 BlockingQueuedConnection cycles.

learner@ksa: ~/gl-q02/m01-l02
learner@ksa:~/gl-q02/m01-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verify -pthreadlearner@ksa:~/gl-q02/m01-l02./verifyMETACALL_OK direct=1 queued=1 cycle_caught=1 scaled_uv=4050learner@ksa:~/gl-q02/m01-l02
strace — learner@ksa: ~/gl-q02/m01-l02
learner@ksa:~/gl-q02/m01-l02strace -e \trace=clone,clone3,futex,write,exit_group ./verifyfutex(0x7a67c487a7bc, 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=0x7a67c41ff990, parent_tid=0x7a67c41ff990, exit_signal=0, stack=0x7a67c39ff000, stack_size=0x7fff80, tls=0x7a67c41ff6c0} => {parent_tid=[459593]}, 88) = 459593futex(0x7a67c41ff990, FUTEX_WAIT_BITSET|FUTEX_CLOCK_REALTIME, 459593, NULL, FUTEX_BITSET_MATCH_ANY) = 0write(1, "METACALL_OK direct=1 queued=1 cy"..., 60) = 60exit_group(0)                           = ?+++ exited with 0 +++

Cross-Thread Signal and Locking Pitfalls

Asynchronous Qt::QueuedConnection value messages keep subsystem boundaries clean up to a few hundred events per second. When an ADC, SPI IMU, or vibration channel streams at 10 kHz, however, allocating 10,000 QMetaCallEvent objects per second overwhelms the GUI event queue—setting the stage for Lesson 1.3's lock-free .

Forcing Qt::DirectConnection Across Threads Onto a QWidget Slot:

  • Symptom: Adding Qt::DirectConnection appears to lower UI update latency in bench tests, then crashes hours later inside QWidgetBackingStore::markDirty.
  • Root Cause: Qt::DirectConnection overrides receiver->thread() and executes the QWidget slot directly on the emitting worker pthread without GUI synchronization.
  • Fix: Omit the 5th argument (Qt::AutoConnection) or specify Qt::QueuedConnection whenever the receiver is a QWidget or main-thread QObject.

Passing Raw C Pointers Over Qt::QueuedConnection:

  • Symptom: A GUI slot connected to void frameReady(const char *buf, int len) reads garbled ASCII or crashes when logging incoming packets.
  • Root Cause: QMetaCallEvent copies only the 8-byte pointer value const char *, while the worker buffer pointed to was overwritten by the next read or popped off the stack.
  • Fix: Emit a value-owning QByteArray, QString, or registered C++ struct (Q_DECLARE_METATYPE) so QMetaCallEvent owns an independent copy or atomic refcount.

Guided Practice

Extend WaitForGraph::enterBlockingQueued() in verify.cpp to test a 3-thread ring (GUI(1) -> Storage(2) -> Network(3) -> GUI(1)) and confirm that cycle detection rejects the closing 3 -> 1 edge before thread 3 sleeps.

Independent Practice

Replace CalStore with a double-buffered std::atomic<std::shared_ptr<const CalCoeffs>> (or index flip) so readers perform zero mutex locks on the hot path while writers publish new immutable calibration snapshots atomically.

Verification Checks

quiz · 1 of 3

In main(), you create worker = new IoWorker(), call connect(this, &Ctrl::trigger, worker, &IoWorker::runStep) (default Qt::AutoConnection), and afterward call worker->moveToThread(&ioThread) and ioThread.start(). When main() emits trigger(), how does runStep() execute?

quiz · 2 of 3

The GUI thread invokes a worker slot via Qt::BlockingQueuedConnection to flush data while the worker is mid-execution emitting a Qt::BlockingQueuedConnection progress query back to the GUI thread. What happens?

quiz · 3 of 3

Why does emitting void adcBurst(const int16_t *samples, int count) from a worker stack array int16_t buf[64] across Qt::QueuedConnection corrupt data?

Key takeaways

  • Qt::AutoConnection evaluates QThread::currentThread() == receiver->thread() on every signal emission, selecting DirectConnection on matching threads and across distinct threads.
  • Qt::QueuedConnection copy-constructs registered QMetaType arguments into a heap QMetaCallEvent posted to the receiver event queue, whereas passing raw pointers to stack buffers causes use-after-return corruption.
  • Qt:: parks the emitting thread on a semaphore until the receiver slot completes, deadlocking instantly on same-thread calls or symmetric two-thread wait cycles.
  • Shared read-mostly configuration or calibration tables accessed across threads use QReadWriteLock with QReadLocker and QWriteLocker instead of synchronous BlockingQueuedConnection RPCs.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure