sho*_*osh 35 c++ multithreading
使用win32线程,我有直接向前GetExitCodeThread()
提供线程函数返回的值.我正在寻找类似的东西std::thread
(或提升线程)
据我所知,这可以通过期货完成,但究竟如何呢?
Ale*_*x B 61
请参阅有关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();
Run Code Online (Sandbox Code Playgroud)
或者std::async
(线程和期货的更高级别包装器):
#include <thread>
#include <future>
int func() { return 1; }
std::future<int> ret = std::async(&func);
int i = ret.get();
Run Code Online (Sandbox Code Playgroud)
我无法评论它是否适用于所有平台(它似乎适用于Linux,但不适用于Mac OSX和GCC 4.6.1).
seh*_*ehe 32
我会说:
#include <thread>
#include <future>
int simplefunc(std::string a)
{
return a.size();
}
int main()
{
auto future = std::async(simplefunc, "hello world");
int simple = future.get();
return simple;
}
Run Code Online (Sandbox Code Playgroud)
请注意,异步甚至会传播从线程函数抛出的任何异常
使用 C++11 线程,无法获取线程退出时的返回值,而以前的情况是这样的pthread_exit(...)
您需要使用C++11Future<>
来获取返回值。Future 是使用模板化参数创建的,其中模板采用返回值(内置用户定义类型)。
您可以使用函数在另一个线程中获取值future<..>::get(..)
。
using 的好处之一future<..>
是您可以检查返回值的有效性,即如果它已经被占用,您可以get()
通过使用函数检查有效性来避免意外调用future<..>::isValid(...)
。
以下是编写代码的方法。
#include <iostream>
#include <future>
using namespace std;
auto retFn() {
return 100;
}
int main() {
future<int> fp = async(launch::async, retFn);
if(fp.valid())
cout<<"Return value from async thread is => "<<fp.get()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
launch::deferred
还应该注意的是,我们可以通过使用选项 as来让未来在同一线程上运行
future<int> fp = async(launch::deferred, retFn);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
64243 次 |
最近记录: |