c++ 超时函数/重试函数包装

// utils.hpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <map>
#include <mutex>
#include <functional>
#include <future>
#include <chrono>
#include <iostream>
#include <optional>


#if _HAS_CXX17
    //1.超时包装函数 c++17
    template<typename  _Rep, typename _Period,typename _F,typename... _Args>
     auto timout_wapper(const std::chrono::duration<_Rep, _Period>& _timout,_F&& _f, _Args&&... _args) -> std::optional<std::invoke_result_t<_F, _Args...>>
    {
        std::future<std::invoke_result_t<_F, _Args...>> res = std::async(std::forward<_F>(_f),std::forward<_Args>(_args)...);
        auto status = res.wait_for(_timout);
        switch (status) {
        case std::future_status::ready:
            return std::optional<std::invoke_result_t<_F, _Args...>>(res.get());
        case std::future_status::timeout:
            return std::optional<std::invoke_result_t<_F, _Args...>>();
        }
    }

    //2.重连包装函数
    	//返回值为bool
     template<typename _Rep,typename _Period,typename _Condition,typename..._Args>
     auto recall_wappper(int retryCount, const std::chrono::duration<_Rep, _Period>& retryint,_Condition&& _f,_Args... _args) 
         -> std::enable_if_t<std::is_same<std::invoke_result_t<_Condition, _Args...>,bool>::value ,bool> 
     {
         while (retryCount-- > 0) {
             std::cout << "retryCount:" << retryCount<<std::endl;
             bool res = std::invoke(std::forward<_Condition>(_f), std::forward<_Args>(_args)...);
             if (res)
                 return true;
             std::this_thread::sleep_for(retryint);
         }
         return false;
     }
     
		//返回值为int,0成功,非0失败
	 template<typename _Rep, typename _Period, typename _Condition, typename..._Args>
	 auto recall_wappper(int retryCount, const std::chrono::duration<_Rep, _Period>& retryint, _Condition&& _f, _Args... _args)
		 -> std::enable_if_t<std::is_same<std::invoke_result_t<_Condition, _Args...>, int>::value, bool>
	 {
		 while (retryCount-- > 0) {
			 std::cout << "retryCount:" << retryCount << std::endl;
			 int res = std::invoke(std::forward<_Condition>(_f), std::forward<_Args>(_args)...);
			 if (res == 0)
				 return true;
			 std::this_thread::sleep_for(retryint);
		 }
		 return false;
	 }
     
#else	//c++11
	namespace std {
		template<typename Functor, typename... Args>
		typename std::enable_if<
			std::is_member_pointer<typename std::decay<Functor>::type>::value,
			typename std::result_of<Functor && (Args&&...)>::type
		>::type invoke(Functor&& f, Args&&... args)
		{
			return std::mem_fn(f)(std::forward<Args>(args)...);
		}

		template<typename Functor, typename... Args>
		typename std::enable_if<
			!std::is_member_pointer<typename std::decay<Functor>::type>::value,
			typename std::result_of<Functor && (Args&&...)>::type
		>::type invoke(Functor&& f, Args&&... args)
		{
			return std::forward<Functor>(f)(std::forward<Args>(args)...);
		}
	}

	template<typename _Rep, typename _Period, typename _Condition, typename..._Args>
	auto recall_wappper(int retryCount, const std::chrono::duration<_Rep, _Period>& retryint, _Condition&& _f, _Args... _args)
		-> typename std::enable_if<std::is_same<typename std::result_of<_Condition && (_Args&&...)>::type, bool>::value, bool>::type
	{
		while (retryCount-- > 0) {
			std::cout << "retryCount:" << retryCount << std::endl;
			bool res = std::invoke(std::forward<_Condition>(_f), std::forward<_Args>(_args)...);
			if (res)
				return true;
			std::this_thread::sleep_for(retryint);
		}
		return false;
	}

	template<typename _Rep, typename _Period, typename _Condition, typename..._Args>
	auto recall_wappper(int retryCount, const std::chrono::duration<_Rep, _Period>& retryint, _Condition&& _f, _Args... _args)
		-> typename std::enable_if<std::is_same<typename std::result_of<_Condition&&(_Args&&...)>::type, int>::value, bool>::type
	{
		while (retryCount-- > 0) {
			std::cout << "retryCount:" << retryCount << std::endl;
			int res = std::invoke(std::forward<_Condition>(_f), std::forward<_Args>(_args)...);
			if (res == 0)
				return true;
			std::this_thread::sleep_for(retryint);
		}
		return false;
	}
#endif

由于 c++17 以前没有 std::option ,所以c++11没实现超时函数的包装

//main.cpp
#include "utils.hpp"
#include <iostream>

//------------------------------------------- 测试 ------------------------------------------
//1.普通函数
int some_task(int value)
{
	std::this_thread::sleep_for(std::chrono::seconds(3));
	return value;
}

//2.成员函数
class plus {
public:
	int work(int a, int b) {
		return a + b;
	}
};

//3.函数对象
class plus2 {
public:
	int operator()(int a, int b) {
		return a + b;
	}
};

bool connect(){
	return false;
}

int main()
{
	//1.普通函数
	auto op = timout_wapper(std::chrono::seconds(1),some_task, 3);
	if (op) {
		std::cout << op.value() << std::endl;
	}
	else {
		std::cout << "timeout\n" << std::endl;
	}

	//2.成员函数
	plus a;
	auto op2 = timout_wapper(std::chrono::seconds(1), &plus::work,a,3,3);
	if (op2) {
		std::cout << op2.value() << std::endl;
	}
	else {
		std::cout << "timeout\n" << std::endl;
	}

	//3.函数对象
	auto op3 = timout_wapper(std::chrono::seconds(1), plus2(), 3, 3);
	if (op3) {
		std::cout << op3.value() << std::endl;
	}
	else {
		std::cout << "timeout\n" << std::endl;
	}

	//4.lambda
	auto op4 = timout_wapper(std::chrono::seconds(1), []() {return 100; });
	if (op4) {
		std::cout << op4.value() << std::endl;
	}
	else {
		std::cout << "timeout\n" << std::endl;
	}
	
	if(recall_wappper(3,std::chrono::seconds(3),connect)){
		std::cout << "connect ok\n" << std::endl;
	}else{
		std::cout << "connect failed\n" << std::endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值