Search code examples
c++multithreadingqtboost

Call a function from another thread


My application has multiple threads on startup. I need thread A to be able to force thread B to run a function(With parameters as well.) I've tried searching on google but could not find what I needed, lots of stack overflow articles that didn't seem to relate to what I was doing. I'm not sure if I'm just using the wrong term for this, and maybe that's why I can't find the information I need. I'm open to using Boost if there is an option in their threading library, and if there is, if you could point me in the direction of some sample code I could look at which does what I need. My application also uses QT already, although I have never used the QT threading lib so I don't know if it includes this either.

Basically what I need to do is this.

//Thread A
void ThreadA()
{
   //Do work to get data
   //Pass Data to another function, and have thread B run it.
   ThreadB.Run(data,arg2,arg3);
}

Solution

  • There's no way to do it explicitly. You can transfer messages between your threads, e.g. using events, which would trigger calling of the method needed. But the target thread must be in loop, waiting for message. It's the only one way you can force the thread to go in another subroutin.

    Abstract example:

    // in ThreadB [the target thread]
    
    std::vector<Message> messages;
    bool wait_message;
    
    // ...
    
    while(wait_message) {
        if(messages.size() > 0) {
            // process messages
        }
    }
    
    // ...
    

    And for another thread:

    // in ThreadA
    
    // ... 
    
    messages.push_back(Message("call_my_method", some_data));
    
    // ... 
    

    Class Message (just for example):

    class Message {
    private:
        std::string _what;
        void* _data;
    
    public:
        Message(const std::string& what, void* data) : _what(what), _data(data) { }
        Message(const Message& inst) : _what(inst._what), _data(inst._data) { }
    
        const std::string& what() const { return _what; }
        void* data() const { return _data; }
    };
    

    For only the function calls, you can use std::function and std::bind and transfer just a callback, which provides some fixed signature (e.g. void(void)), with your message.