Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::async on a member function?

How can I operate std::async call on a member function?

Example:

class Person{ public:     void sum(int i){         cout << i << endl;     } };  int main(int argc, char **argv) {     Person person;     async(&Person::sum,&person,4); } 

I want to call to sum async.

Person p; call async to p.sum(xxx) 

I didnt figure out if i can do it with std::async. Dont want to use boost. Looking for a one line async call way.

like image 544
Avihai Marchiano Avatar asked Dec 02 '12 12:12

Avihai Marchiano


People also ask

How does STD async work?

std::async works without a launch policy, so std::async(square, 5); compiles. When you do that the system gets to decide if it wants to create a thread or not. The idea was that the system chooses to make a thread unless it is already running more threads than it can run efficiently.

Does STD async use thread pool?

How does std::launch::async Work in Different Implementations? For now, we know that if no policy is specified, then std::async launches a callable function in a separate thread. However, the C++ standard does not specify whether the thread is a new one or reused from a thread pool.

What is C++ std async?

async( std::launch policy, Function&& f, Args&&... args ); (since C++20) The function template async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call.


1 Answers

Something like this:

auto f = std::async(&Person::sum, &p, xxx); 

or

auto f = std::async(std::launch::async, &Person::sum, &p, xxx); 

where p is a Person instance and xxx is an int.

This simple demo works with GCC 4.6.3:

#include <future> #include <iostream>  struct Foo {   Foo() : data(0) {}   void sum(int i) { data +=i;}   int data; };  int main() {   Foo foo;   auto f = std::async(&Foo::sum, &foo, 42);   f.get();   std::cout << foo.data << "\n"; } 
like image 114
juanchopanza Avatar answered Oct 02 '22 21:10

juanchopanza