Search code examples
c++asynchronousmember

Can't do async run member function in other class


I try to async to member function in other class but can't. this is overview in my code

#include <iostream>
#include <thread>
#include <future>
#include <vector>

using namespace std;
class Work
{
public:
    void doWork(int A);
};

 void Work::doWork(int A)
{
    cout<<"I got "<<A<<endl;    
}   

class Worker
{
private:
    vector<int> work_list;
    Work* workset = NULL;
public:
    void Work_MP();
};
void Worker::Work_MP()
{
    vector<std::future<void>> v_async;
    v_async.reserve(8);
    for (size_t i = 0; i < 8; i++)
    {   
        Work* workset = new Work();
        v_async.emplace_back(std::async(std::launch::async, &Work::doWork, &workset, i));
    }   
}

int main ()
{
}

Although, I give pointer about other class function and instance. didn't work. Is other needed statement missing?


Solution

  • I tried to fix your code and came up with a version that is working. You have a lot of unecessary cluttering in there. Also your code will leak the workset pointer. As pointed out in the comments the main mistake was the &workset which created a "ref to pointer" where all you need was the pointer itself. You should avoid the plain pointers altogether. This is what I came up with, hope it helps:

    #include <vector>
    #include <future>
    #include <iostream>
    
    class Work
    {
    public:
        void doWork(int A){
            std::cout << "I got " << A << std::endl;    
        }
    };
    
    class Worker
    {
    public:
        void Work_MP(){
            std::vector< std::future<void> > v_async;
            v_async.reserve( 8 );
            for( size_t i = 0; i < 8; ++i ){   
                std::shared_ptr<Work> workset = std::make_shared<Work>();
                v_async.emplace_back( std::async( std::launch::async, &Work::doWork, workset, i ) );
            }  
        }
    };
    
    int main ()
    {
        Worker worker;
        worker.Work_MP();
        return 0;
    }
    

    As you can see I inlined the function definition for briefness. Converted the plain pointer to shared pointer and removed unused vars.

    See it in action here: https://onlinegdb.com/vFQo8R1rA