See this video tutorial on C++11 futures.
Explicitly with threads and futures:
#include <thread>
#include <future>
void func(std::promise<int> && p) {
p.set_value(1);
}
std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();
Or with std::async
(higher-level wrapper for threads and futures):
#include <thread>
#include <future>
int func() { return 1; }
std::future<int> ret = std::async(&func);
int i = ret.get();
I can't comment whether it works on all platforms (it seems to work on Linux, but doesn't build for me on Mac OSX with GCC 4.6.1).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…