std::future 将阻塞当前线程,等待std::promise设置future的值。
这里由于std::future 是阻塞的,因此肯定无法在当前线程中,给std::promise设置值了,肯定需要在创建的新线程中来设置
std::future。
于是我们写如下测试代码:
#include <iostream>
#include <thread>
#include <future>
#include <windows.h>
void thread_func(std::promise<int> *robj)
{
std::cout << "Inside thread" << std::endl;
Sleep(5000);
robj->set_value(100);
}
int main()
{
std::promise<int> pobj;
std::future<int> fu = pobj.get_future();
std::thread th(thread_func,&pobj);
std::cout << fu.get() << std::endl;
th.join();
std::cout << "Hello World!\n";
}

博客介绍了std::future会阻塞当前线程,需在新线程中为std::promise设置值。并给出测试代码,创建新线程调用函数设置std::promise的值,主线程通过std::future获取该值,最后展示了完整代码示例。
1251

被折叠的 条评论
为什么被折叠?



