C++Future简单的使用,参考c++并发编程指南
#include "stdafx.h" #include <thread> #include <iostream> #include <vector> #include <algorithm> #include <map> #include <mutex> #include <stack> #include <string> #include <exception> #include <memory> // For std::shared_ptr<> #include <queue> #include <condition_variable> #include <atomic> #include <future> using namespace std; int Add() { cout << "Future add exe!" << endl; return 1; } int Sum(int a, int b) { return a + b; } struct MySum { int Sum(int a, int b){ return a + b; } }; int _tmain(int argc, _TCHAR* argv[]) { std::future<int> the_answer = std::async(std::launch::async/*std::launch::deferred*/, Add); // 通过延时来看期望的两个选项的差异(std::launch::async --- 异步线程执行,std::launch::deferred --- 延时执行) this_thread::sleep_for(chrono::seconds(10)); std::cout << "The answer is " << the_answer.get() << std::endl; std::future<int> the_sum = std::async(Sum, 1, 2); std::cout << "The Sum is " << the_sum.get() << std::endl; MySum TheStructSum; std::future<int> StructSum = std::async(&MySum::Sum, TheStructSum, 3, 4); std::cout << "The Struct Sum is " << StructSum.get() << std::endl; return 0; }