In Qt, it is possible to execute a lambda or a functor in a specific thread using metacall posting. Here's how it's done:
Create a functoid to wrap the function to be executed:
Pass the function to be executed as an argument to the std::function class as shown:
std::function<void()> myFunction = []() { // Code to be executed in the specified thread };
Post the metacall to the specified thread:
Use the postMetaCall function from the FunctorCallConsumer namespace to post the metacall to the desired thread. The function takes a thread pointer and a function pointer as arguments.
FunctorCallConsumer::postMetaCall(&myThread, myFunction);
QMetaObject::invokeMethod(&myThread, myFunction);
Implement a metacall event consumer:
The final step is to implement a QEvent subclass that will receive and execute the metacall. The FunctorCallEvent class can be defined as follows:
class FunctorCallEvent : public QEvent { public: FunctorCallEvent(std::function<void()> fun) : QEvent(QEvent::None), m_fun(fun) {} void execute() { m_fun(); } private: std::function<void()> m_fun; };
Connect the event consumer to the thread:
Once the FunctorCallEvent class has been defined, connect it to the event loop of the specified thread using QCoreApplication::installEventFilter.
QCoreApplication::instance()->installEventFilter(new FunctorCallEventConsumer(&myThread));
Example:
Here's a complete example that demonstrates how to execute a lambda in a specified thread:
#include <QtCore> class MyThread : public QThread { public: void run() override { // Execute the lambda in this thread m_lambda(); } void setLambda(std::function<void()> lambda) { m_lambda = lambda; } private: std::function<void()> m_lambda; }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // Create a new thread MyThread thread; // Create a lambda to execute in the thread std::function<void()> lambda = []() { qDebug() << "Lambda executed in thread" << QThread::currentThread(); }; // Set the lambda on the thread thread.setLambda(lambda); // Start the thread thread.start(); return app.exec(); }
Output:
Lambda executed in thread QThread(0x7f8632802640, name = "MyThread")
The above is the detailed content of How to Execute a Functor or Lambda in a Specific Qt Thread?. For more information, please follow other related articles on the PHP Chinese website!