c语言中定时执行线程alarm,用多线程写一个alarm,

已结贴√

问题点数:20 回复次数:3

ca56232b3bbedf9a539d07f37fffb99a.gif

3144d8b7615c79d9f638db40d5689d26.gif

a218af6549b45ee526caf607ebff1358.gif

0f8df0e29816ae721419de940fb833d1.gif

用多线程写一个alarm,

#include

#include

#include

#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<

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<time:"<time<<

"    sleep_time:"<

"     alarm->message:"<message<

#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<seconds:"<seconds<<

"  alarm->message:"<message<

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<

last=&alarm_list;        //last存放的 alarm_list的地址,alarm_list的内容为空

next=*last;                //next指向当前结点也就是alarm_list的内容,第一次内容为空

//cout<

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<

for(next=alarm_list;next!=NULL;next=next->link)

cout<time:"<time<<

"    next->time-time(NULL):"<time-time(NULL)<<

"   next->message:"<message<

#endif

status=pthread_mutex_unlock(&alarm_mutex);//操作完毕,解锁

if(status!=0)

err_abort(status,"Unlock mutex");

}

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值