Class and std::async on class member in C++

后端 未结 2 1290
感情败类
感情败类 2021-02-03 22:19

I\'m try to write a class member which calls another class member multiple times in parallel.

I wrote a simple example of the problem and can\'t even get to compile this

相关标签:
2条回答
  • 2021-02-03 22:21

    You can pass the this pointer to a new thread:

    async([this]()
    {
        Function(this);
    });
    
    0 讨论(0)
  • 2021-02-03 22:34

    do_rand_stf is a non-static member function and thus cannot be called without a class instance (the implicit this parameter.) Luckily, std::async handles its parameters like std::bind, and bind in turn can use std::mem_fn to turn a member function pointer into a functor that takes an explicit this parameter, so all you need to do is to pass this to the std::async invocation and use valid member function pointer syntax when passing the do_rand_stf:

    auto hand=async(launch::async,&A::do_rand_stf,this,i,j);
    

    There are other problems in the code, though. First off, you use std::cout and std::endl without #includeing <iostream>. More seriously, std::future is not copyable, only movable, so you cannot push_back the named object hand without using std::move. Alternatively, just pass the async result to push_back directly:

    ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));
    
    0 讨论(0)
提交回复
热议问题