除了std::thread,我们还可以使用 tasks.
tasks和std::thread工作的方式非常相似,只有一个最主要的不同:tasks可以返回一个值。因此,你可以暂存这个返回值来作为这个线程的更抽象的定义方式,并在你真的需要返回的结果的时候来从这个返回值中拿到数据。
1 #include <future>
2 //Tasks, Future, and Promises
3 {
4 auto f1 = [](std::vector<int> &v,
5 unsigned int left, unsigned int right) {
6 unsigned long long acm = 0;
7 for (unsigned int i = left; i < right; ++i)
8 {
9 acm += v[i];
10 }
11
12 return acm;
13 };
14
15 auto t1 = std::async(f1, std::ref(v),
16 0, v.size() / 2);
17 auto t2 = std::async(f1, std::ref(v),
18 v.size() / 2, v.size());
19
20 //You can do other things here!
21 unsigned long long acm1 = t1.get();
22 unsigned long long acm2 = t2.get();
23
24 std::cout << "acm1: " << acm1 << endl;
25 std::cout << "acm2: " << acm2 << endl;
26 std::cout << "acm1 + acm2: " << acm1 + acm2 << endl;
27 }
2.std::async的返回值是一个叫std::future的类型。别被他的名字唬到,他的意思是t1和t2的值会在未来被真正的赋值。我们通过调用t1.get()来获得他的真正的返回值。
4.注意,我们传递给std::async的函数(实际上是lambda表达式)是有返回值的,这个返回值用过一个叫做std::promise的类型来传递。大多数情况下你不需要了解任何promise的细节,C++在幕后可以处理好这些事情。
创建线程很简单,你可以通过函数指针、伪函数、lambda表达式的方式来创建std::thread,也可以使用std::async的方式来获得一个std::future类型的返回值。std::async也同样可以使用函数指针、伪函数、lambda表达式来创建