promise和future
C++11使用std::future和std::promise在线程中传递变量实现异步操作。
网上找到的示意图:
promise成员函数:
- std::promise::get_future
- std::promise::set_value
- std::promise::set_exception
- std::promise::set_value_at_thread_exit: 在线程退出时该 promise 对象会自动设置为 ready(注意:该线程已设置promise的值,如果在线程结束之后有其他修改共享状态值的操作,会抛出future_error(promise_already_satisfied)异常)
- std::promise::swap:交换 promise 的共享状态
std::future常用function:
- std::future::get: 获取值
- std::future::wait: 等待状态为ready,无返回值
- std::future::wait_for: 等待一段时间,返回std::future_status
std::future_status三种状态:
- deferred:异步操作还没开始
- ready:异步操作已经完成
- timeout:异步操作超时
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
int main() {
std::promise<int> p;
std::thread thread_([&p]{
std::cout << "thead_id: " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
p.set_value(10);
});
std::cout << "main thread_id: " << std::this_thread::get_id() << std::endl;
std::future_status status;
auto f= p.get_future();
//调用get()会阻塞直到状态为ready
//auto v = f.get();
//std::cout << "v: " << v << std::endl;
do {
status = f.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::timeout) {
std::cout << "timeout..." << std::endl;
} else if (status == std::future_status::ready) {
int val = f.get();
std::cout << "ready, val: " << val << std::endl;
} else {
std::cout << "other..." << std::endl;
}
} while (status != std::future_status::ready);
thread_.join();
return 0;
}