Reputation: 2647
I am converting my code to multi thread to performance enhancement.
I have vector of shared_ptr and an object of another class and I am passing a shared_ptr from vector and an object as parameter to function. I am calling it using std::async but it is giving me following error :
line from where I am making async call : required from here
/usr/include/c++/4.8.2/functional1697.61: error: no type named 'type'
in 'class std::result_of<void (*(std::shared_ptr<A>, B))
(const std::shared_ptr<A>&, B&)>'typedef typename
result_of<_Callable(_Args...)>::type result_type;
Here is code snippet :
void foo(std::vector<std::shared_ptr<A>>& a, B b){
std::vector<std::future<void>> tasks;
for(auto& sptr : a ){
tasks.push_back(std::async(std::launch::async, foo1, a, b))
}
void foo1(const std::shared_ptr<A>& a, B& b ){
//do some stuff
}
Can you please help me. Thanks
Upvotes: 3
Views: 2471
Reputation: 171433
I am converting my code to multi thread to performance enhancement.
Here we go ... I predict difficulties.
The error is telling you that the result of calling foo1
with the arguments that std::async
will pass to it is not defined, i.e. you can't call the function with those arguments.
The reason is that the function foo1
takes a parameter of type B&
but std::async
copies its arguments and forwards the copies to the target function, so it is going to copy b
and then call foo1
with that copy forwarded as an rvalue, which cannot be bound to an lvalue reference of type B&
.
If you really want to pass b
by reference then you need to wrap it:
std::async(std::launch::async, foo1, a, std::ref(b))
However you should be careful, it looks like every thread is going to have a non-const reference to the same B
object, implying they might be modifying that object concurrently, which will lead to data races (and undefined behaviour) unless B
is already thread-safe or you modify the function foo1
to synchronize access to B
.
Just sprinkling multithreaded pixie dust on your code is not going to make it faster if the code is not safe to use in multiple threads.
Upvotes: 5