問題描述
使用 win32 線程,我可以直接使用 GetExitCodeThread()
來獲取線程函數返回的值.我正在為 std::thread
(或 boost 線程)尋找類似的東西
據我所知,這可以通過期貨來完成,但究竟如何?
With win32 threads I have the straight forward GetExitCodeThread()
that gives me the value which the thread function returned. I'm looking for something similar for std::thread
(or boost threads)
As I understand this can be done with futures but how exactly?
推薦答案
參見 關于 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
(線程和期貨的高級包裝器):
Or with std::async
(higher-level wrapper for threads and futures):
#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).
I can't comment whether it works on all platforms (it seems to work on Linux, but doesn't build for me on Mac OSX with GCC 4.6.1).
這篇關于C++:來自 std::thread 的簡單返回值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!