第一篇讲的是高级线程函数async();
第二篇,这篇讲低级线程函数thread(),和它的promise-结果收集器。
#include<iostream>
#include<thread>
#include<future>
#include<string>
#include<exception>
#include<stdexcept>
#include<functional>
#include<utility>
void doSomething(std::promise<std::string> &p)
{
try
{
std::cout << "read a char:";
char c = std::cin.get();
if (c=='x')
{
throw std::runtime_error(std::string("char ") + c + " read");
}
std::string s = std::string("char ") + c + " processed";
p.set_value(std::move(s));//填写结果;
}
catch (...)
{
p.set_exception(std::current_exception()); //填写异常;
}
}
int main()
{
try
{
std::promise<std::string>p;//定义结果收集器;
std::thread t(doSomething,std::ref(p));//1,把结果收集器传进去。2,std::ref这是模板变量传引用的方式。3,必须传引用;
t.detach();
std::future<std::string> f(p.get_future());//取得future;只能取一次。取多次会有异常;
std::cout << "result:" << f.get() << std::endl;//从future取得结果;结果也只能取一次,取多次会有异常;
}
catch (const std::exception& e)
{
std::cerr << "exception:" << e.what() << std::endl;
} catch (...)
{
std::cerr << "exception" << std::endl;
}
std::cout << "all done" << std::endl;
getchar();
getchar();
return 0;
}