std::shared_future, std::async, std::launch
#include <thread>
#include <future>
#include <iostream>
using std::thread,
std::promise,
std::future,
std::shared_future,
std::cerr;
int main(){
int test = 0;
promise<int> p, p1, p2;
shared_future<int> sfuture(p.get_future());
auto task_lambda1 = [sfuture](promise<int>* pr, int l, int* t)->int{
int n = l * 3 + *t;
pr->set_value(n);
sfuture.wait();
return *t;
};
auto task_lambda2 = [sfuture](promise<int>* pr, int l, int* t)->int{
int n = l *5 + *t;
pr->set_value(n);
sfuture.wait();
return n;
};
future<int> a = p1.get_future();
future<int> b = p2.get_future();
future<int> result1 = std::async(std::launch::async, task_lambda1, &p1, 10, &test);
future<int> result2 = std::async(std::launch::async, task_lambda2, &p2, 10, &test);
// these work if uncommented but don't forget to uncomment
// the join() calls below.
// thread s(task_lambda1, &p1, 10, &test);
// thread t(task_lambda2, &p2, 10, &test);
// these do not work. pretty sure they're not supposed to
// in this situation
// task_lambda1(&p1, 10);
// task_lambda2(&p2, 10);
a.wait();
b.wait();
test = 17;
// this is necessary to get everything going
p.set_value(0);
// these work if uncommented
// cerr << "a: " << a.get() << "\n";
// cerr << "b: " << b.get() << "\n";
cerr << "result1: " << result1.get() << "\n";
cerr << "result2: " << result2.get() << "\n";
// s.join();
// t.join();
return 0;
}
C++ Examples© 2024 TBD