Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Most elegant way to call method in an object in another thread
Forum Updated to NodeBB v4.3 + New Features

Most elegant way to call method in an object in another thread

Scheduled Pinned Locked Moved Solved General and Desktop
2 Posts 2 Posters 398 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    Tarae
    wrote on last edited by
    #1

    I have a simple class:

    class MyClass
    {
    public:
        int getWorkResult() { return doSomeWork(); }
    private:
        int doSomeWork();
    };
    

    I want to be able to call getWorkResult() from every thread of my program. But doSomeWork() must always run in the same thread, because of synchronization.
    What is the best way? I want calling getWorkResult() from all the threads be simple as possible. I don't mind that threads may be waiting for a while to the result.

    My solution so far:

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        MyClass()
        {
            connect(this, &MyClass::getWorkResultSignal, 
                    this, &MyClass::getWorkResultSlot,
                    Qt::BlockingQueuedConnection);
        }
    
        int getWorkResult()
        {
            int result;
            emit getWorkResultSignal(&result);
            return result;
        }
    signals:
         void getWorkResultSignal(int * returnValue);
    private slots:
         void getWorkResultSlot(int * returnValue){ &returnValue = doSomeWork(); }
    private:
         int doSomeWork();  
    }
    

    Now I can call getWorkResult() really simply in every thread:

    int result = myClass->getWorkResult();
    

    Is my solution correct? Is there a better solution?

    1 Reply Last reply
    0
    • Chris KawaC Offline
      Chris KawaC Offline
      Chris Kawa
      Lifetime Qt Champion
      wrote on last edited by Chris Kawa
      #2

      You can just do

      int getWorkResult()
      {
          int result;
          QMetaObject::invokeMethod(this, &MyClass::doSomeWork, &result);
          return result;
      }
      

      This will do all the connection plumbing for you.

      1 Reply Last reply
      2

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved