Skip to content

Instantly share code, notes, and snippets.

@tiandiao123
Created December 21, 2022 21:45
Show Gist options
  • Save tiandiao123/675165a451ed186f8b92f5701edba144 to your computer and use it in GitHub Desktop.
Save tiandiao123/675165a451ed186f8b92f5701edba144 to your computer and use it in GitHub Desktop.
#include <future>
#include <iostream>
#include <thread>
using namespace std;
int factorial(std::shared_future<int> f){
int N = f.get();
int res = 1;
for(int i=2;i<=N;i++){
res *= i;
}
return res;
}
int main(){
std::promise<int> p;
std::future<int> f = p.get_future();
std::shared_future<int> sf = f.share();
std::future<int> fu = std::async(std::launch::async,factorial, sf);
std::future<int> fu2 = std::async(std::launch::async,factorial, sf);
std::future<int> fu3 = std::async(std::launch::async,factorial, sf);
// do something else
std::this_thread::sleep_for(chrono::milliseconds(1000));
p.set_value(6);
int x = fu.get();
cout <<"the result x is : " << x << endl;
// p.set_value(8);
int x2 = fu2.get();
cout <<"the result x2 is : " << x << endl;
int x3 = fu3.get();
cout << "the result x3 is: " << x3 << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment