How to execute a functor or a lambda in a given thread in Qt, GCD-style?
Problem:
In ObjC with GCD, you can execute a lambda in any of the threads that spin an event loop using dispatch_sync or dispatch_async functions. It executes something (equivalent to [] { /* do sth */ } in C ) in the main thread's queue, either blocking or asynchronously. How can you do the same in Qt?
Solution:
In Qt, you can achieve a similar behavior by delivering an event that wraps the functor to a consumer object residing in the desired thread, a process known as metacall posting. Here's how you can do it:
Qt 5.10 & up TL;DR
// invoke on the main thread QMetaObject::invokeMethod(qApp, []{ ... }); // invoke on an object's thread QMetaObject::invokeMethod(obj, []{ ... }); // invoke on a particular thread QMetaObject::invokeMethod(QAbstractEventDispatcher::instance(thread), []{ ... });
TL;DR for functors Qt 5.10 & up
// https://github.com/KubaO/stackoverflown/tree/master/questions/metacall-21646467 // Qt 5.10 & up - it's all done template <typename f> static void postToObject(F &&fun, QObject *obj = qApp) { QMetaObject::invokeMethod(obj, std::forward<f>(fun)); } template <typename f> static void postToThread(F && fun, QThread *thread = qApp->thread()) { auto *obj = QAbstractEventDispatcher::instance(thread); Q_ASSERT(obj); QMetaObject::invokeMethod(obj, std::forward<f>(fun)); }</f></typename></f></typename>
TL;DR for methods/slots Qt 5.10 & up
// Qt 5/4 template <typename t typename r> static void postToObject(T * obj, R(T::* method)()) { struct Event : public QEvent { T * obj; R(T::* method)(); Event(T * obj, R(T::*method)()): QEvent(QEvent::None), obj(obj), method(method) {} ~Event() { (obj->*method)(); } }; if (qobject_cast<qthread>(obj)) qWarning() <p><strong>Qt 5.10 & up TL;DR: What about a single shot timer?</strong></p> <pre class="brush:php;toolbar:false">template <typename f> static void postToObject(F && fun, QObject * obj = qApp) { if (qobject_cast<qthread>(obj)) qWarning() (fun)); }</qthread></typename>
Common Code Qt 5.10 & up
#ifndef HAS_FUNCTORCALLCONSUMER namespace FunctorCallConsumer { bool needsRunningThread() { return true; } QObject * forThread(QThread * thread) { Q_ASSERT(thread); QObject * target = thread == qApp->thread() ? static_cast<qobject>(qApp) : QAbstractEventDispatcher::instance(thread); Q_ASSERT_X(target, "postMetaCall", "the receiver thread must have an event loop"); return target; } } #endif</qobject>
Qt 4/5 Solution Using a Temporary Object as The Signal Source
#include <qtcore> #include <functional> namespace FunctorCallConsumer { QObject * forThread(QThread*); } #define HAS_POSTMETACALL void postMetaCall(QThread * thread, const std::function<void> & fun) { QObject signalSource; QObject::connect(&signalSource, &QObject::destroyed, FunctorCallConsumer::forThread(thread), [=](QObject*){ fun(); }); } #ifdef __cpp_init_captures void postMetaCall(QThread * thread, std::function<void> && fun) { QObject signalSource; QObject::connect(&signalSource, &QObject::destroyed, FunctorCallConsumer::forThread(thread), [fun(std::move(fun))](QObject*){ fun(); }); } #endif</void></void></functional></qtcore>
Qt 4/5 Solution Using QEvent Destructor
#include <qtcore> #include <functional> class FunctorCallEvent : public QEvent { std::function<void> m_fun; QThread * m_thread; public: FunctorCallEvent(const std::function<void> & fun, QObject * receiver) : QEvent(QEvent::None), m_fun(fun), m_thread(receiver->thread()) {} FunctorCallEvent(std::function<void> && fun, QObject * receiver) : QEvent(QEvent::None), m_fun(std::move(fun)), m_thread(receiver->thread()) { qDebug() <p><strong>Qt 5 Solution Using the Private QMetaCallEvent</strong></p> <pre class="brush:php;toolbar:false">#include <qtcore> #include <private> #include <functional> class FunctorCallEvent : public QMetaCallEvent { public: template <typename functor> FunctorCallEvent(Functor && fun, QObject * receiver) : QMetaCallEvent(new QtPrivate::QFunctorSlotObject<functor typename qtprivate::list_left>::Value, void> (std::forward<functor>(fun)), receiver, 0, 0, 0, (void**)malloc(sizeof(void*))) {} };</functor></functor></typename></functional></private></qtcore>
Qt 4/5 Solution Using a Custom Event and Consumer
#include <qtcore> #include <functional> class FunctorCallEvent : public QEvent { std::function<void> m_fun; public: FunctorCallEvent(const std::function<void> & fun, QObject *) : QEvent(QEvent::None), m_fun(fun) {} FunctorCallEvent(std::function<void> && fun, QObject *) : QEvent(QEvent::None), m_fun(std::move(fun)) { qDebug() Map; static QObject * m_appThreadObject; static QMutex m_threadObjectMutex; static Map m_threadObjects; bool event(QEvent * ev) { if (!dynamic_cast<functorcallevent>(ev)) return QObject::event(ev); static_cast<functorcallevent>(ev)->call(); return true; } };</functorcallevent></functorcallevent></void></void></void></functional></qtcore>
The above is the detailed content of How to Execute Functors or Lambdas in Specific Qt Threads?. For more information, please follow other related articles on the PHP Chinese website!

This article explains the C Standard Template Library (STL), focusing on its core components: containers, iterators, algorithms, and functors. It details how these interact to enable generic programming, improving code efficiency and readability t

This article details efficient STL algorithm usage in C . It emphasizes data structure choice (vectors vs. lists), algorithm complexity analysis (e.g., std::sort vs. std::partial_sort), iterator usage, and parallel execution. Common pitfalls like

This article details effective exception handling in C , covering try, catch, and throw mechanics. It emphasizes best practices like RAII, avoiding unnecessary catch blocks, and logging exceptions for robust code. The article also addresses perf

The article discusses using move semantics in C to enhance performance by avoiding unnecessary copying. It covers implementing move constructors and assignment operators, using std::move, and identifies key scenarios and pitfalls for effective appl

C 20 ranges enhance data manipulation with expressiveness, composability, and efficiency. They simplify complex transformations and integrate into existing codebases for better performance and maintainability.

The article discusses dynamic dispatch in C , its performance costs, and optimization strategies. It highlights scenarios where dynamic dispatch impacts performance and compares it with static dispatch, emphasizing trade-offs between performance and

Article discusses effective use of rvalue references in C for move semantics, perfect forwarding, and resource management, highlighting best practices and performance improvements.(159 characters)

C memory management uses new, delete, and smart pointers. The article discusses manual vs. automated management and how smart pointers prevent memory leaks.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools