If I want to get the result from a thread, which of the following code is correct? Or there exists better way to achieve the same goal?
void foo(int &result) {
result = 123;
}
int bar() {
return 123;
}
int main() {
int foo_result;
std::thread t1(foo, std::ref(foo_result));
t1.join();
std::future<int> t2 = std::async(bar);
int bar_result = t2.get();
}
And another case,
void baz(int beg, int end, vector<int> &a) {
for (int idx = beg; idx != end; ++idx) a[idx] = idx;
}
int main() {
vector<int> a(30);
thread t0(baz, 0, 10, ref(a));
thread t1(baz, 10, 20, ref(a));
thread t2(baz, 20, 30, ref(a));
t0.join();
t1.join();
t2.join();
for (auto x : a) cout << x << endl;
}