我試着編寫一個類成員,並行調用另一個類成員多次。在C++中的類成員上的類和std :: async
我寫了一個簡單的例子,甚至無法編譯這個問題。我在調用std :: async時做錯了什麼?我想這個問題會與我如何傳遞函數有關。
#include <vector>
#include <future>
using namespace std;
class A
{
int a,b;
public:
A(int i=1, int j=2){ a=i; b=j;}
std::pair<int,int> do_rand_stf(int x,int y)
{
std::pair<int,int> ret(x+a,y+b);
return ret;
}
void run()
{
std::vector<std::future<std::pair<int,int>>> ran;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
auto hand=async(launch::async,do_rand_stf,i,j);
ran.push_back(hand);
}
}
for(int i=0;i<ran.size();i++)
{
pair<int,int> ttt=ran[i].get();
cout << ttt.first << ttt.second << endl;
}
}
};
int main()
{
A a;
a.run();
}
編譯:(隱式this
參數)
g++ -std=c++11 -pthread main.cpp
通'* this'作爲第三個參數爲'async'。 – Xeo 2012-08-01 11:44:09
如果您在編譯或鏈接時遇到錯誤,在問題中包含這些錯誤,最好是逐字記錄將是一個好主意。 – 2012-08-01 11:44:50
您不需要再使用pthread與C++ 11 :)這是C++ 11(線程)中最大的添加之一。如果異步啓動和顯式線程也存在於語言本身中,則async()是隱式線程。 – siddhusingh 2012-11-15 09:31:04