如何利用多线程写一个简单的定时器?

972 篇文章 329 订阅
32 篇文章 6 订阅

       先来看一个简单的程序, 实现一个定时器来定时调用test函数:

 

#include <iostream>
#include <windows.h>
using namespace std;

void test()
{
	cout << "test" << endl;
}

DWORD WINAPI ThreadFun(LPVOID pM)
{
	int timeVal = *(int *)pM;
	while(1)
	{
		test();

		Sleep(timeVal); // 3s调用一次test
	}

	return 0;
}

int main()
{
	int timeVal = 3000;
	HANDLE handle = CreateThread(NULL, 0, ThreadFun,  &timeVal, 0, NULL);
	CloseHandle(handle);

	while(1);

	return 0;
}

       然而, 上述是有问题的, 没有考虑test函数本身的执行时间, 例如, 下面程序实际上是5秒执行一次test

 

 

#include <iostream>
#include <windows.h>
using namespace std;

void test()
{
	cout << "test" << endl;
	Sleep(2000);
}

DWORD WINAPI ThreadFun(LPVOID pM)
{
	int timeVal = *(int *)pM;
	while(1)
	{
		int start = GetTickCount();  
		test();

		Sleep(timeVal); // 实际是5s调用一次test
	}

	return 0;
}

int main()
{
	int timeVal = 3000;
	HANDLE handle = CreateThread(NULL, 0, ThreadFun,  &timeVal, 0, NULL);
	CloseHandle(handle);

	while(1);

	return 0;
}

      改进后的程序为:

 

 

#include <iostream>
#include <windows.h>
using namespace std;

void test()
{
	cout << "test" << endl;
	Sleep(2000); // 假设此处不超过3s
}

DWORD WINAPI ThreadFun(LPVOID pM)
{
	int timeVal = *(int *)pM;
	while(1)
	{
		int start = GetTickCount();  
		test();
		
		while(GetTickCount() - start < timeVal)
		{
			Sleep(10);
		}
	}

	return 0;
}

int main()
{
	int timeVal = 3000;
	HANDLE handle = CreateThread(NULL, 0, ThreadFun,  &timeVal, 0, NULL);
	CloseHandle(handle);

	while(1);

	return 0;
}

        该程序是3s调用一次test函数。

 


        诚然, 上述程序也没有考虑一些特殊和异常的情况(比如test函数本身时间超过3s, 那代码就有问题了), 在本文中, 我们仅仅讨论一种可行的方法, 如果在具体项目中, 还需要更加完善更加健壮的代码。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值