我正在使用vc2011,事实证明std :: async(std :: launch :: async,...)有点儿错误(有时它不会产生新线程并且并行运行它们,而是重用线程和一个接一个地运行任务).当我进行昂贵的网络呼叫时,这太慢了.所以我想我会编写自己的异步函数.我虽然陷入困境,std :: promise应该在哪里生活?在1)线程函数中,2)异步函数,或3)调用函数.
码:
#include <future>
#include <thread>
#include <iostream>
#include <string>
#include <vector>
std::string thFun() {
throw std::exception("bang!");
return "val";
}
std::future<std::string> myasync(std::promise<std::string>& prms) {
//std::future<std::string> myasync() {
//std::promise<std::string> prms; //needs to outlive thread. How?
std::future<std::string> fut = prms.get_future();
std::thread th([&](){
//std::promise<std::string> prms; //need to return a future before...
try {
std::string val = thFun();
prms.set_value(val);
} catch(...) {
prms.set_exception(std::current_exception());
}
});
th.detach();
return fut;
}
int main() {
std::promise<std::string> prms; //I really …Run Code Online (Sandbox Code Playgroud)