c++多线程(十四) - std::future_status

    c++中, std::future_status的定义如下:

enum class future_status
{
	ready,      //成功
	timeout,    //超时
	deferred    //延迟
};

1. future_status::ready  

    线程myThread执行5秒,wait_for等待了6s,所以线程myThread已经执行完毕,future_status的值为ready 。

#include
#include
#include
#include
using namespace std;

int myThread()
{
	cout << "Thread start id = " << this_thread::get_id() << endl;
	chrono::milliseconds time(5000); //休息5秒
	this_thread::sleep_for(time);
	cout << "Thread end id = " << this_thread::get_id() << endl;
	return 5;
}

int main()
{
	cout << "Main start id = " << this_thread::get_id() << endl;
	future result = async(myThread);
	cout << "continue......" << endl;
	//等待6秒
	std::future_status status = result.wait_for(std::chrono::seconds(6));
	//超时,线程还没执行完
	if (status == std::future_status::ready)
	{
		cout << "线程执行完" << endl;
	}	 
	//成功,线程已经执行完
	else if (status == std::future_status::timeout)
	{
		cout << "线程超时" << endl;
	}
	//延迟,async第一个参数被设置为std::launch::deferred
	else if (status == std::future_status::deferred)
	{
		cout << "线程延迟执行" << endl;
	}
	return 0;
}

    执行结果

  c++多线程(十四) - std::future_status_第1张图片

2. future_status::timeout

     线程myThread执行5秒,wait_for等待了1s,所以线程myThread超时,future_status的值为timeout。

//等待1秒
std::future_status status = result.wait_for(std::chrono::seconds(1));

    执行结果

  c++多线程(十四) - std::future_status_第2张图片

3. future_status::deferred

    线程myThread延迟执行,future_status的值为deferred。

//线程延迟执行
future result = async(std::launch::deferred, myThread);

    执行结果

 c++多线程(十四) - std::future_status_第3张图片

你可能感兴趣的:(C++)