/*
通过链表实现定时器,后台一个线程倒计时(遍历链表的节点),若一个节点的数到0,则采取一定的动作
*/
#include"stdio.h"
#include"pthread.h"
#include"string.h"
#include"stdlib.h"
#define Success 0
#define Failure -1
struct Time
{
int iTimeId;
char cFlag;
int (*fun)();
int iTimeValues;
int iTemp;
struct Time *next;
};
struct Time *head = NULL;
struct Time *tail = NULL;
pthread_mutex_t testlock;
void DelTime(int iTime)
{
struct Time *p = head;
struct Time *q = head->next;
pthread_mutex_lock(&testlock);
while ( NULL != q)
{
if ( q->iTimeId == iTime)
{
p->next = q->next;
free(q);
q = p->next;
}
p = p->next;
q = q->next;
}
if ( head->iTimeId == iTime)
{
p = head ;
head = head->next;
free(p);
p = NULL;
}
pthread_mutex_unlock(&testlock);
}
int TimeLibInit()
{
struct Time *pst = head;
while(1)
{
sleep(1);
while(NULL != pst)
{
if ('R' == pst->cFlag)
{
if (pst->iTemp > 0)
{
pst->iTemp = pst->iTemp-1;
}
else
{
(*(pst->fun))();
pst->cFlag='S';
// DelTime();
break;
}
}
else
{
;
}
pst = pst->next;
}
pst = head;
}
}
int TimeCreate(int itime,void (*f)())
{
static int iNum=1;
pthread_mutex_lock(&testlock);
if(1 == iNum)
{
struct Time *p=(struct Time *)malloc(sizeof(struct Time));
p->iTimeId=iNum;
p->cFlag='S';
p->iTimeValues=itime;
p->iTemp =itime;
p->fun=f;
head = tail = p;
tail->next = NULL;
}
else
{
struct Time *p=(struct Time *)malloc(sizeof(struct Time));
p->iTimeId=iNum;
p->cFlag='S';
p->iTimeValues=itime;
p->iTemp =itime;
p->fun=f;
tail->next = p;
tail = p;
tail->next = NULL;
}
pthread_mutex_unlock(&testlock);
}
int TimeStart(int iId)
{
struct Time *pst = head;
while(pst)
{
if(pst->iTimeId == iId)
{
pst->cFlag = 'R';
return 0;
}
}
return -1;
}
void PrintMoring()
{
printf("good moring\n");
}
void PrintAfternoon()
{
printf("good afternoon\n");
}
int main()
{
int err;
pthread_t tid;
int ichioce;
pthread_mutex_init(&testlock, NULL);
err=pthread_create(&tid,NULL,TimeLibInit,NULL);
if(err=0)
printf("can’t create thread:%s\n",strerror(err));
while(1)
{
printf("1.add a timer\n");
printf("2.start a timer\n");
printf("input your chioce:\n");
scanf("%d",&ichioce);
switch(ichioce)
{
case 1 :
TimeCreate(10,PrintMoring);
break;
case 2 :
TimeStart(1);
break;
default:
break;
}
}
pthread_mutex_destroy(&testlock);
return 0;
}
转载于:https://my.oschina.net/sharelinux/blog/115383