#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后,自动退出
本文介绍了使用C++实现多线程中定时任务的处理方式。通过创建自定义结构体和线程函数,实现了线程间的数据传递及根据不同条件终止线程的功能。展示了如何设置线程运行时间限制并优雅地处理超时情况。
3万+

被折叠的 条评论
为什么被折叠?



