当前位置 : 主页 > 编程语言 > c++ >

C:std :: thread的简单返回值?

来源:互联网 收集:自由互联 发布时间:2021-06-23
使用win32线程,我有直接的GetExitCodeThread(),它给出了线程函数返回的值.我正在为std :: thread(或boost线程)寻找类似的东西 据我所知,这可以通过期货完成,但究竟如何呢? 关于C 11期货,请参见
使用win32线程,我有直接的GetExitCodeThread(),它给出了线程函数返回的值.我正在为std :: thread(或boost线程)寻找类似的东西
据我所知,这可以通过期货完成,但究竟如何呢? 关于C 11期货,请参见 this video tutorial.

明确与线程和期货:

#include <thread>
#include <future>

void func(std::promise<int> && p) {
    p.set_value(1);
}

std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();

或者使用std :: async(线程和期货的更高级别包装器):

#include <thread>
#include <future>
int func() { return 1; }
std::future<int> ret = std::async(&func);
int i = ret.get();

我无法评论它是否适用于所有平台(它似乎适用于Linux,但不适用于Mac OSX和GCC 4.6.1).

网友评论