C++并发低层接口std::thread和std::promis

2019-08-29  本文已影响0人  土豆吞噬者

std::thread用于启动和处理线程,相比高级接口std::async,它不提供这些性质:

void print123()
{
    for (int i = 0; i < 3; i++) {
        cout << i + 1 << endl;
        this_thread::sleep_for(chrono::milliseconds(100));
    }
}

int main()
{
    thread t(print123);//启动线程
    cout << "thread id:" << t.get_id() << endl;//输出线程id
    t.join();//等待线程结束
    system("pause");
}

如果你想传递参数给线程,你可以像async那样,如果你想获取返回值,可以使用引用传递参数。另一个获取返回值的方式是使用std::promise,promise在线程里通过set_xxxx方法设置值或异常(线程安全的),在线程外通过get_future方法(只能调用一次)获取一个future对象,然后调用get方法等待set_xxxx方法执行(同样也只能调用一次get方法)。

void getValue(promise<string>& result)
{
    try {
        this_thread::sleep_for(chrono::seconds(10));
        result.set_value("hello");
    }catch (...) {
        result.set_exception(current_exception());
    }
}

 

int main()
{
    promise<string> result;
    thread t(getValue,ref(result));
    t.detach();
    auto f = result.get_future();
    cout << f.get() << endl;
    system("pause");
}

如果你想在线程结束时才收到数据可以使用set_value_at_thread_exit/set_exception_at_thread_exit。

void getValue(promise<string>& result)
{
    try {
        this_thread::sleep_for(chrono::seconds(10));
        result.set_value_at_thread_exit("hello");
    }catch (...) {
        result.set_exception_at_thread_exit(current_exception());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读