美文网首页
C++并发低层接口std::thread和std::promis

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

作者: 土豆吞噬者 | 来源:发表于2019-08-29 18:09 被阅读0次

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

  • thread没有启动策略,它创建后就会尝试启动一个新线程执行任务,如果不能启动新线程则产生异常。
  • thread没有接口可处理线程结果。
  • 如果线程中有未被处理的异常,程序会立刻终止,要想将异常传播到线程外,可以使用exception_ptr。
  • 在thread销毁前你必须调用join方法等待线程结束或detach方法使它不受控制,否则程序会立刻终止。
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());
    }
}

相关文章

网友评论

      本文标题:C++并发低层接口std::thread和std::promis

      本文链接:https://www.haomeiwen.com/subject/hrlwectx.html