用多线程写一个alarm,
#include <iostream>#include <ctime>
#include <cstdio>
#include "errors.h"
#define DEBUG
using namespace std;
typedef struct alarm_tag
{
struct alarm_tag *link;
int seconds;
time_t time; //seconds from epoch(公元,纪年)
char message[64];
}alarm_t;
pthread_mutex_t alarm_mutex=PTHREAD_MUTEX_INITIALIZER;
alarm_t *alarm_list=NULL;
//The alarm thread's start routine.
void *alarm_thread(void *arg)
{
alarm_t *alarm;
int sleep_time;
time_t now;
int status;
while(true)
{
status=pthread_mutex_lock(&alarm_mutex);//下面要对数据进行操作,加锁
if(status!=0)
err_abort(status,"Lock mutex");
// cout<<"thread 2:"<<alarm_list<<endl;
alarm=alarm_list;
if(alarm==NULL)//此时无要处理的message
sleep_time=1;
else //alarm_lists是aralm_thread与main的共享数据
{
alarm_list=alarm->link;
now=time(NULL);
if(alarm->time<=now)
sleep_time=0;
else
sleep_time=alarm->time-now;
#ifdef DEBUG
cout<<"waiting alarm->time:"<<alarm->time<<
" sleep_time:"<<sleep_time<<
" alarm->message:"<<alarm->message<<endl;
#endif
}
status=pthread_mutex_unlock(&alarm_mutex);//操作完毕,解锁
if(status!=0)
err_abort(status,"Unlock mutex");
if(sleep_time>0)
sleep(sleep_time);
else
sched_yield();
if(alarm!=NULL)
{
cout<<"aralm not empty! alarm->seconds:"<<alarm->seconds<<
" alarm->message:"<<alarm->message<<endl;
free(alarm);
alarm=NULL;
}
}
}
int main()
{
int status;
char line[128];
alarm_t *alarm,**last,*next;
pthread_t thread;
status=pthread_create(&thread,NULL,alarm_thread,NULL);
if(status!=0)
err_abort(status,"Create alarm thread");
while(true)
{
if(fgets(line,sizeof(line),stdin)==NULL)
exit(0);
if(strlen(line)<=1)
continue;
alarm=(alarm_t*)malloc(sizeof(alarm_t));//申请
if(alarm==NULL)
errno_abort("Allocate alarm");
if(sscanf(line,"%d %64[^\n]",&alarm->seconds,alarm->message)<2)//^忽略\n,不读入字符串
{
fprintf(stderr,"Bad command\n");
free(alarm);
alarm=NULL;
}
else
{
status=pthread_mutex_lock(&alarm_mutex);//要操作数据,加锁
if(status!=0)
err_abort(status,"Lock mutex");
alarm->time=time(NULL)+alarm->seconds;
// cout<<"thread 1:"<<alarm_list<<endl;
last=&alarm_list; //last存放的 alarm_list的地址,alarm_list的内容为空
next=*last; //next指向当前结点也就是alarm_list的内容,第一次内容为空
//cout<<"next:"<<next<<endl;
while(next!=NULL)
{
if(next->time>=alarm->time)
{
alarm->link=next;
*last=alarm;
break;
}
last=&next->link;
next=next->link;
}
if(next==NULL)
{
*last=alarm;//last改变相当于aralm_list改变
alarm->link=NULL;
}
#ifdef DEBUG
cout<<"List: ";
for(next=alarm_list;next!=NULL;next=next->link)
cout<<"next->time:"<<next->time<<
" next->time-time(NULL):"<<next->time-time(NULL)<<
" next->message:"<<next->message<<endl;
#endif
status=pthread_mutex_unlock(&alarm_mutex);//操作完毕,解锁
if(status!=0)
err_abort(status,"Unlock mutex");
}
}
return 0;
}