Skip to content

Instantly share code, notes, and snippets.

@conqp
Last active July 2, 2021 10:22
Show Gist options
  • Save conqp/de935ebbc295bb73718fe26640b26ca6 to your computer and use it in GitHub Desktop.
Save conqp/de935ebbc295bb73718fe26640b26ca6 to your computer and use it in GitHub Desktop.
Wrapper for a promise and a corresponding future
#include <future>
#include <iostream>
#include <thread>
template <typename T>
class PromiseFuture {
private:
std::promise<T> promise;
std::future<T> future;
public:
PromiseFuture()
: promise(std::promise<T>()), future(promise.get_future())
{}
void operator=(T const & value)
{
promise.set_value(value);
}
operator T()
{
return future.get();
}
};
int sum(int a, int b)
{
return a + b;
}
int main()
{
PromiseFuture<int> result1;
PromiseFuture<int> result2;
std::thread t1([&](){ result1 = sum(1, 2); });
std::thread t2([&](){ result2 = sum(3, 4); });
std::cout << result1 << "\n";
std::cout << result2 << "\n";
t1.join();
t2.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment