C++11多线程:std::future的其他成员函数:wait_for(等待一定的时间)。

系列文章目录



前言

std::future的其他成员函数:

std::future的用法:参考连接
https://blog.csdn.net/weixin_55491446/article/details/129695136?spm=1001.2014.3001.5501

主要内容:
(1)get()函数转移数据;
(2)wait_for(等待一定的时间)。
持续更新中。


一、wait_for()的用法

wait_for(等待一定的时间)

//执行一个异步线程
std::future<int> result = std::async(std::launch::deferred, mythread);
//等待异步线程几秒
std::future_status status = result.wait_for(std::chrono::seconds(4));

三种返回结果:

  1. 超时:我想等待你1秒钟,希望你返回,你没有返回,那么status = timeout
status == std::future_status::timeout
  1. 完成:表示线程成功返回;
status == std::future_status::ready
  1. 延迟:如果async的第一个参数被设置为std::launch::deferred,则本条件成立
status == std::future_status::deferred

二、使用步骤

2.1 代码示例1

这里设置线程执行5秒,等待线程6秒

#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(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;
}

运行截图1:
在这里插入图片描述

2.2 代码示例2

这里设置线程执行5秒,等待线程4秒

修改函数参数:

//wait_for(等待一定的时间)
std::future_status status = result.wait_for(std::chrono::seconds(4));

运行截图2:
在这里插入图片描述


总结

了解wait_for(等待一定的时间)的使用;
持续更新中…

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴躁茹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值