一、wait_for和get、wait的区别
(1)future.get,等待着拿到函数的返回值为止,当future是deferred时,会调用这个函数并等待。
(2)future.wait,等待线程返回,本身并不返回结果,当future是deferred时,会调用这个函数并等待。
(3)future.wait_for(等待一定的时间),当future是deferred时,直接返回的是std::future::deferred
,并且不会调用这个函数。
二、wait_for的三种返回结果
超时:我想等待你1秒钟,希望你返回,你没有返回,那么status = timeout;
status == std::future_status::timeout
完成:表示线程成功返回;
status == std::future_status::ready
延迟:如果async的第一个参数被设置为std::launch::deferred,则本条件成立
status == std::future_status::deferred
三、代码举例
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <thread>
#include <list>
#include <mutex>
#include <future>
using namespace std;
int mythread()
{
cout << "mythread() start" << " threadid = " << std::this_thread::get_id() << endl; //新线程id
std::chrono::milliseconds dura(5000); //订一个5秒的时间
std::this_thread::sleep_for(dura); //休息了一定时长
cout << "mythread() end" << " threadid = " << std::this_thread::get_id() << endl;
return 5;
}
int main()
{
//一:std::future的其他成员函数,get()函数转移数据
cout << "main" << " threadid = " << std::this_thread::get_id() << endl;
std::future<int> result = std::async(std::launch::async, mythread);
//线程并不会卡在这里
//std::future<int> result = std::async(std::launch::deferred, mythread);
cout << "continue...!" << endl;
//cout << result.get() << endl;
//卡在这里等待线程执行完,
//但是这种get因为一些内部特殊操作,不能get多次,只能get一次
//枚举类型:
//wait_for(等待一定的时间)
std::future_status status = result.wait_for(std::chrono::seconds(6));
//等待1秒
if (status == std::future_status::timeout)
//超时:我想等待你1秒钟,希望你返回,你没有返回,那么status = timeout
{
//表示线程还没执行完;
cout << "超时,线程还没有执行完毕" << endl;
}
else if (status == std::future_status::ready)
{
//表示线程成功返回
cout << "线程成功执行完毕,返回" << endl;
cout << result.get() << endl;
}
else if (status == std::future_status::deferred)
{
//如果async的第一个参数被设置为std::launch::deferred,则本条件成立
cout << "线程被延迟执行" << endl;
cout << result.get() << endl;
}
cout << "I Love China!" << endl;
return 0;
}
// 当async调用时
main threadid = 3720
continue...!
mythread() start threadid = 28316
mythread() end threadid = 28316
线程成功执行完毕,返回
5
I Love China!
// 当deferred调用时
main threadid = 24840
continue...!
线程被延迟执行
mythread() start threadid = 24840
mythread() end threadid = 24840
5
I Love China!
重新设置wait_for时间为4s
// 当async调用时
main threadid = 17312
continue...!
mythread() start threadid = 15724
超时,线程还没有执行完毕
I Love China!
mythread() end threadid = 15724
// 当deferred调用时
main threadid = 24840
continue...!
线程被延迟执行
mythread() start threadid = 24840
mythread() end threadid = 24840
5
I Love China!