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

新手上路,请多包涵

对于 win32 线程,我有直接的 GetExitCodeThread() 这给了我线程函数返回的值。我正在为 std::thread (或增强线程)寻找类似的东西

据我了解,这可以通过期货来完成,但究竟如何?

原文由 shoosh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 965
2 个回答

请参阅有关 C++11 期货的 视频教程

明确地使用线程和期货:

 #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,但不适用于我在带有 GCC 4.6.1 的 Mac OSX 上构建)。

原文由 Alex B 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用以下带有线程和期货的代码创建一组线程:

 #include <thread>
#include <future>

void func(promise<float> && prms) {

    prms.set_value(0.125);

}

主要是:

 vector<pair<thread, future<float>>> threads;

for (int i = 0; i < std::thread::hardware_concurrency(); i++) {

                promise<float> prms;
                future<float> fut = prms.get_future();

                ///Triggering threads
                thread th(func, move(prms));
                ///Pushing thread and result to vector
                threads.push_back(make_pair(move(th), move(fut)));

        }
        cout<< "Killing threads ... \n";
        for (auto& e : threads)
        {
            auto th = move(e.first);
            auto fut = move(e.second);
            float flt = fut.get();
            //cout << flt << endl;
            th.detach();
        }

原文由 Hamed Hasibi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题