自学pthread
#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)
sleep_time=1;
else
{
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<<"("<<sleep_time<<")"<<"'"<<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<<"("<<alarm->seconds<<")"<<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)
{
cout<<"alarm> ";
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)
{
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;
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->message<<"---]"<<endl;
#endif
status=pthread_mutex_unlock(&alarm_mutex);//操作完毕,解锁
if(status!=0)
err_abort(status,"Unlock mutex");
}
}
return 0;
}
没看太理解申请为每个闹钟申请空间然后加到alarm_list 中是怎么加的。
请各位指教。