std::future与std::promise通信机制
请解释C++中std::future和std::promise的工作原理,以及如何在两个线程间传递数据。
回答
我还是少年
std::promise<T>和std::future<T>构成一个一次性通信通道。promise设置值/异常,future获取值/异常。
void producer(std::promise<int> p) {
std::this_thread::sleep_for(1s);
p.set_value(42); // 设置结果
}
void consumer(std::future<int> f) {
int val = f.get(); // 阻塞等待结果
std::cout << val;
}
std::promise<int> p;
auto f = p.get_future();
std::thread t1(producer, std::move(p));
std::thread t2(consumer, std::move(f));
t1.join(); t2.join();
注意:promise和future只能移动不可复制;get()只能调用一次;可在promise上调用set_exception()传递异常。