在学习C++11有关promise 的问题
我想用promise实现在线程中放入数据,在主线程中读取数据,可是一次可以,多次就不可以了。
promise可以这样用吗,难到只是一次读取吗?
测试代码如下:
#include <thread>c++11?future?promise
#include <future>
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
#include <functional>
#include <utility>
void doSomething (std::promise<std::string>& p)
{
try {
// read character and throw exceptiopn if ’x’ //
int i = 0;
while(i++ < 10)
{
std::cout << "read char (’x’ for exception): ";
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)); // store result
}
}
catch (...) {
p.set_exception(std::current_exception()); // store exception
}
}
int main()
{
try {
// start thread using a promise to store the outcome
std::promise<std::string> p;
std::cout<<"step0"<<std::endl;
std::thread t(doSomething,std::ref(p));
std::cout<<"step1"<<std::endl;
t.detach();
std::cout<<"step2"<<std::endl;
// create a future to process the outcome
int i = 0;
std::future<std::string> f(p.get_future());
while(i++ < 10)
{
// process the outcome
std::cout << "result: " << f.get() << std::endl;
}
}
catch (const std::exception& e) {
std::cerr << "EXCEPTION: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "EXCEPTION " << std::endl;
}
}