Reputation: 21
Here's my code:
#include <iostream>
#include <future>
#include <thread>
#include <vector>
using namespace std;
vector <int> exec(vector <int> &a, vector <int> &b) {
vector <int> res = a;
res.push_back(b[0]);
res.push_back(b[1]);
res.push_back(b[2]);
res.push_back(b[3]);
return res;
}
int main() {
vector <int> a1{ 1, 2, 3, 4 }, a2{ 5, 6, 7 , 8 };
std::packaged_task<vector <int>(vector <int>, vector <int>)> task(exec);
std::future<vector <int>> ret = task.get_future();
std::thread th(std::move(task), a1, a2);
th.detach();
vector <int> P1 = ret.get();
for (auto i = 0; i < P1.size(); ++i) {
cout << P1[i];
}
cout << endl;
system("pause");
return 0;
}
Using -std=c++17 or -std=c++14 Clang always throws me one error:
In file included from Source.cpp:2:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\future:568:6: error: no
matching constructor for initialization of 'function<std::vector<int,
std::allocator<int> > (std::vector<int, std::allocator<int> >, std::vector<int,
std::allocator<int> >)>'
: _Fn(_Fnarg)
^ ~~~~~~
And it also throws me a couple of warnings. The same thing goes for g++. I use Visual Studio 2015 and clang 6.0.0. What's the matter?
Upvotes: 1
Views: 49
Reputation: 62613
You need packaged_task
types match function types. In particular, since I assume you'd like to keep references for exec
:
std::packaged_task<vector<int> (vector<int>&, vector<int>&)> task(exec);
std::future<vector <int>> ret = task.get_future();
std::thread th(std::move(task), std::ref(a1), std::ref(a2));
Upvotes: 1
Reputation: 40150
Your exec
function takes references to vectors, but you define your task and future with an underlying function taking vector's copies. Either change exec
or task
definition.
I'd advise changing exec
type to:
std::vector<int> exec(std::vector<int> base, std::vector<int> const &b) {
base.push_back(b[0]);
base.push_back(b[1]);
base.push_back(b[2]);
base.push_back(b[3]);
return base;
}
and task
to:
std::packaged_task<std::vector<int>(std::vector<int>, std::vector<int> const&)> task(exec);
Upvotes: 0