c语言怎么实现多个计时器?且要互不干扰下面是单个计时器程序
真正的定时器,不能靠循环的,它不稳定且Sleep占CPU的且更不可能互不干扰
它要用系统的功能,可用系统本身定时器或多线程实现,以下是windows下两个不同定时器的实现参考
#include <windows.h> #include <stdio.h> #pragma link "user32.lib" static BOOL Exit1 = FALSE; static BOOL Exit2 = FALSE; const UINT Timer1 = 10; const UINT Timer2 = 11; VOID CALLBACK Timer1Fun( HWND h, UINT u1, UINT u2, Dword d ) { static int count=120; //120秒,2分种 if (count==0) { printf("时间1到!!! "); Exit1 = TRUE; return; } if (count%5==0 || count<5) { //5秒一输出 printf("定时器1:%d秒 ",count); } count--; } VOID CALLBACK Timer2Fun( HWND h, UINT u1, UINT u2, Dword d ) { static int count=120; //120秒,2分种 if (count==0) { printf("时间2到!!! "); Exit2 = TRUE; return; } if (count%10==0 || count<10) { //10秒一输出 printf("定时器2:%d秒 ",count); } count--; } int main() { MSG msgFoo; SetTimer( NULL, Timer1, 1000, Timer1Fun ); //1秒一次 SetTimer( NULL, Timer2, 1000, Timer2Fun ); //1秒一次 while( !(Exit1 && Exit2) && GetMessage( &msgFoo, NULL, 0, 0 ) ) { TranslateMessage( &msgFoo ); DispatchMessage( &msgFoo ); } KillTimer( NULL, Timer1 ); KillTimer( NULL, Timer2 ); return 0; }