stl-thread-002

第一篇講的是高級線程函數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;
}
發佈了39 篇原創文章 · 獲贊 8 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章