重点:利用sleep() 和GetTickCount() 函数
sleep(100L)是占用cpu,线程休眠100毫秒,其他进程不能再占用cpu资源,wait(100L)是进入等待池中等待,交出cpu等系统资源供其他进程使用,在这100毫秒中,该线程可以被其他线程notify,但不同的是其他在等待池中的线程不被notify不会出来,但这个线程在等待100毫秒后会自动进入就绪队列等待系统分配资源,换句话说,sleep(100)在100毫秒后肯定会运行,但wait在100毫秒后还有等待os调用分配资源,所以wait100的停止运行时间是不确定的,但至少是100毫秒。
函数原型:
DWORD GetTickCount(void);
函数作用:
1、一般用作定时相关的操作。GetTickCount() 返回开机以来经过的毫秒数
2、在要求误差不大于1毫秒的情况下,可以采用GetTickCount()函数,该函数的返回值是DWORD型,表示以毫秒为单位的计算机启动后经历的时间间隔。使用下面的编程语句,可以实现50毫秒的精确定时,其误差小于1毫秒。
#include <iostream>
#include <windows.h>
#include <cmath>
#define PI 3.14
using namespace std;
int main()
{
int starttime;
int busytime;
int sinval = 0;
while(1)
{
starttime = GetTickCount();
busytime = (int)(500 * sin(float((sinval) %= 30) / 30 * 2 * PI)) + 500;
cout << busytime << endl;
sinval++;
while(GetTickCount() - starttime < busytime)
;
Sleep(1000 - busytime);
}
return 0;
}
如果要是cpu 曲线成为一条直线的话,可以使它的busytime 恒小于某个值。
#include <iostream>
#include <windows.h>
#include <cmath>
using namespace std;
int main()
{
int starttime;
int busytime = 500;
int sinval = 0;
while(1)
{
starttime = GetTickCount();
cout << busytime << endl;
sinval++;
while(GetTickCount() - starttime < busytime)
;
Sleep(1000 - busytime);
}
return 0;
}