C++设置一个函数的运行时间,如果超时,就跳过该函数

本文介绍了使用C++实现多线程中定时任务的处理方式。通过创建自定义结构体和线程函数,实现了线程间的数据传递及根据不同条件终止线程的功能。展示了如何设置线程运行时间限制并优雅地处理超时情况。
#include<Windows.h>
#include<iostream>
#include<tchar.h>
#include<string>
#include<ctime>
using namespace std;

struct mytime//定义一个传入函数的结构体
{
	int t1;
	int t2;
};


DWORD WINAPI f1(LPVOID lpParameter)//定义一个需要运行的函数
{
	mytime* t = (mytime*)lpParameter;
	cout << t->t1 << "   " << t->t2 << endl;
	Sleep(t->t1 + t->t2);
	return 0;
}


int main()
{
	clock_t start_time = clock();
	mytime T = { 3000,5000 };
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, f1, &T, 0, NULL);//运行f1函数,并传入结构体参数
	

	int signal=WaitForSingleObject(hThread1, 4000);//设置运行4s
    //如果超出4s,则跳过该函数
	if (signal != WAIT_OBJECT_0)
	{
		cout << "time out" << endl;
		TerminateProcess(hThread1, -1);
	}
	CloseHandle(hThread1);

	clock_t end_time = clock();
	cout << "The run time is: " << (double)(end_time-start_time) / CLOCKS_PER_SEC << "s" << endl;
}
3000   5000
time out
The run time is: 4.001s

原本该函数应该睡眠8s后,退出,由于定时4s,所以超时后,直接退出了该函数。

#include<Windows.h>
#include<iostream>
#include<tchar.h>
#include<string>
#include<ctime>
using namespace std;

struct mytime
{
	int t1;
	int t2;
};


DWORD WINAPI f1(LPVOID lpParameter)
{
	mytime* t = (mytime*)lpParameter;
	cout << t->t1 << "   " << t->t2 << endl;
	Sleep(t->t1 + t->t2);
	return 0;
}


int main()
{
	clock_t start_time = clock();
	mytime T = { 3000,5000 };
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, f1, &T, 0, NULL);
	

	int signal=WaitForSingleObject(hThread1, INFINITE);//一直等到f1函数运行完

	if (signal != WAIT_OBJECT_0)
	{
		cout << "time out" << endl;
		TerminateProcess(hThread1, -1);
	}
	CloseHandle(hThread1);

	clock_t end_time = clock();
	cout << "The run time is: " << (double)(end_time-start_time) / CLOCKS_PER_SEC << "s" << endl;
}
3000   5000
The run time is: 8.001s

如果不设置定时,那么就会直到该函数运行8s后,自动退出

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值