先贴例子,具体知识后续补充。。。
#include <future>
#include <thread>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
int& queryNumber (int& num)
{
// read number
cout << "read number: ";
// int num;
cin >> num;
// throw exception if none
if (!cin) {
throw runtime_error("no number read");
}
return num;
}
void doSomething (char c, shared_future<int&> f)
{
try {
// wait for number of characters to print
int num = f.get(); // get result of queryNumber()
for (int i=0; i<num; ++i) {
this_thread::sleep_for(chrono::milliseconds(500));
cout.put(c).flush();
}
}
catch (const exception& e) {
cerr << "EXCEPTION in thread " << this_thread::get_id()
<< ": " << e.what() << endl;
}
}
void ChangeNum(shared_future<int&> f) {
// int& num = f.get();
auto& num = f.get();
cout << typeid(num).name() << endl;
num += 4;
}
int main()
{
try {
int num;
// start one thread to query a number
// shared_future<int&> f = async(queryNumber,ref(num));
auto f = async(queryNumber, ref(num)).share();
// start three threads each processing this number in a loop
auto f1 = async(ChangeNum, f);
f1.wait();
auto f2 = async(launch::async, doSomething, '+', f);
auto f3 = async(launch::deferred, doSomething, '*', f);
auto f4 = async(doSomething, '.', f);
auto f5 = async(doSomething, '~', f);
//注意:wait_for和wait_until不会启动一个被推迟的任务--线程
// 如果f4被推迟了,这里直接返回future_status::deferred
auto t = f4.wait_for(chrono::seconds(6));
if ( t == future_status::ready) {
cout << "f4 enter ready\n";
f4.wait();
}
if (f5.wait_until(chrono::system_clock::now() + chrono::seconds(60)) == future_status::deferred) {
cout << "f5 enters feferred.\n";
f5.wait();
}
// wait for all loops to be finished
f1.get();
f2.get();
f3.get();
f4.get();
f5.get();
}
catch (const exception& e) {
cout << "\nEXCEPTION: " << e.what() << endl;
}
cout << "\ndone" << endl;
}
输出: