Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 << "
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...