Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multithreading with function in other class

I’m new to c++ so sorry if obvious answer. I’m trying to get a thread to run a function from another class with an argument.

Here’s how my code is laid out:

int main(){ 
    Engine engine; 
    Sounds sounds; 
    std::thread t(&Sounds::ManageSounds, &sounds, &engine) 
    /*some stuff*/
    t.join();
} 
    
class Sounds{ 
    void ManageSounds(Engine en){ 
        /*some stuff*/ 
    } 
}

If I run this code as is, I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error: static assertion failed: std::thread arguments must be
invocable after conversion to rvalues 129 |
typename decay<_Args>::type…>::value

If I change ManageSounds() to accept no arguments and remove the &engine in the thread, it works completely fine.

>Solution :

Your thread method ManageSounds requires an Engine parameter by value, and you pass it a pointer to Engine (&engine).

To fix it you should do one of the following:

  1. Pass the engine object iteslf (if it is copyable, and it makes sense in your case).
  2. If you actually need pointer/reference semantics (which is quite reasonable), change the thread method accordingly. In this case you need to use std::ref (because the ctor of std::thread copies the arguments). Note: you must ensure the thread does not out-live the engine object.

Complete code example (using copy):

#include <thread>

class Engine { /*...*/ };

class Sounds {
public:
    void ManageSounds(Engine en) {
        /*some stuff*/
    }
};

int main() {
    Engine engine;
    Sounds sounds;
    //--------------------------------------------vvvvvv
    std::thread t(&Sounds::ManageSounds, &sounds, engine);
    /*some stuff*/
    t.join();
}

Complete code example (using a reference):

#include <thread>

class Engine { /*...*/ };

class Sounds {
public:
    //-----------------------v
    void ManageSounds(Engine & en) {
        /*some stuff*/
    }
};

int main() {
    Engine engine;
    Sounds sounds;
    //--------------------------------------------vvvvvvvvvvvvvvvv
    std::thread t(&Sounds::ManageSounds, &sounds, std::ref(engine));
    /*some stuff*/
    t.join();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading