- 論壇徽章:
- 0
|
利用C語言函數(shù),一般在一個(gè)進(jìn)程中只能有一個(gè)定時(shí)器。要想實(shí)現(xiàn)多定時(shí)器,一般是在這個(gè)定時(shí)器中使用累計(jì)計(jì)數(shù)來實(shí)現(xiàn)。當(dāng)定時(shí)器比較多,和定時(shí)間隔差別很大,如0.02秒和10秒,計(jì)數(shù)就帶來了很大的額外開銷。
當(dāng)然也可用循環(huán)嵌入sleep,nanosleep的方法,但是這增加了循環(huán)內(nèi)不必要的阻塞。
多進(jìn)程和多線程的方法,增加了程序的復(fù)雜度和開銷。
利用FreeBSD的kqueue可以在單進(jìn)程中實(shí)現(xiàn)多定時(shí)器, 同時(shí)避免以上弊端。
下面是我寫的一小段代碼,與大家共享,獻(xiàn)丑了,呵呵。轉(zhuǎn)載請(qǐng)標(biāo)明來自CU。
- #include <stdio.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/event.h>
- #include <sys/time.h>
- int main()
- {
- struct kevent changes[3];
- struct kevent events[3];
- int kq=kqueue();
- if(kq==-1)
- {
- fprintf(stderr,"Kqueue error: %s\n",strerror(errno));
- return -1;
- }
- struct timespec thetime;
- bzero(&thetime,sizeof(thetime));
-
- EV_SET(&changes[0],0,EVFILT_TIMER, EV_ADD | EV_ENABLE, 0, 5000, 0);
- EV_SET(&changes[1],1,EVFILT_TIMER, EV_ADD | EV_ENABLE, 0, 2000, 0);
- EV_SET(&changes[2],2,EVFILT_TIMER, EV_ADD | EV_ENABLE, 0, 1000, 0);
- if(kevent(kq,changes,3,NULL,0,&thetime)==-1)
- {
- fprintf(stderr,"kevent error: %s\n",strerror(errno));
- return -1;
- }
- for(;;)
- {
- int nev=kevent(kq,NULL,0,events,1,&thetime);
-
- if(nev==-1)
- {
- fprintf(stderr,"kevent error: %s\n",strerror(errno));
- return -1;
- }
-
- if(nev>0)
- {
- int i;
- for(i=0;i<nev;i++)
- {
-
- switch(events[i].ident)
- {
- case 0:
- fprintf(stdout, "This is 5 sec timer.\n");
- break;
- case 1:
- fprintf(stdout, "This is 2 sec timer.\n");
- break;
- case 2:
- fprintf(stdout, "This is 1 sec timer.\n");
- break;
- }
- }
- }
- /*
- ----------可以做其他事情。
- */
- }
-
- return 0;
- }
復(fù)制代碼
[ 本帖最后由 doctorjxd 于 2007-11-16 22:32 編輯 ] |
評(píng)分
-
查看全部評(píng)分
|