跨线程处理异常

#include <iostream>
#include <future>

void work(std::promise<int> &promise){

    try{
     throw std::logic_error("hello");
    }catch (...) {
        promise.set_exception(std::current_exception());//获取当前的异常
    }
}

void handle(std::future<int> &future){
    try {

        std::cout<<future.get()<<std::endl;

    }catch (std::exception &e)
    {
        std::cout<<"exception "<<e.what()<<std::endl;//在另外的线程中处理异常
    }


}

int main()
{
    std::promise<int> promise;
    std::future<int> future = promise.get_future();
    std::thread t1(work,std::ref(promise));
    std::thread t2(handle,std::ref(future));
    t1.join();
    t2.join();

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容