互斥量-mutual exclusion Posix API提供了互斥量的安全函数,
#include<pthread.h>
int phread_mutex_init(phread_mutex_t * tid,void * atrr);
int pthread_mutex_lock(pthread_mutex_t *tid);
int pthread_mutex_unlock(pthread_mutex_t * tid);
int pthread_mutex_trylock(pthread_mutex_t * tid);
API 返回0为成功!一般返回一个正数的出错,在这里用----char * strerror(int errno );
返回错误消息!
测试案例:
#include "unip.h"
/*
mutual exclusing controls muti-alarming requestions;
*/
typedef struct alarm_tag{
struct alarm_tag *link;
int seconds;
time_t times;
char message[MAX];
}alarm_t;
alarm_t * alarm_list=NULL;
pthread_mutex_t alarm_mutex=PTHREAD_MUTEX_INITIALIZER;
void * alarm_thread(void *arg)
{
alarm_t * alarm;
int sleep_time;
time_t now;
int status;
while(1)
{
status=pthread_mutex_lock(&alarm_mutex);
if(status!=0)
Err_quit("mutex_lock error!");
now=time(NULL);
alarm=alarm_list;
if(alarm==NULL)
sleep_time=1;
else
{
alarm_list=alarm_list->link;
if(alarm->times<=now)
{
sleep_time=0;
}
else
sleep_time=alarm->times-now;
printf("[waiting:%ld(%d)\"%s\"]\n",alarm->times,alarm->seconds,alarm->message);
}
status=pthread_mutex_unlock(&alarm_mutex);
if(status!=0)
Err_quit("mutex_lock error!");
if(sleep_time>0)
{
sleep(sleep_time);
}
else
sched_yield();
if(alarm!=NULL)
{
printf("output:%d-----%s\n",alarm->seconds,alarm->message);
free(alarm);
}
}
}
int main(int argc, char const *argv[])
{
time_t now;
int seconds;
int status;
alarm_t *alarm,*next,**last,*head;
char line[MAX];
char message[MAX];
memset(message,0,MAX);
memset(line,0,MAX);
pthread_t tid;
status=pthread_create(&tid,NULL,alarm_thread,NULL);
if(status!=0)
{
Err_quit("here pthread_create error!");
}
while(1){
printf("alarm>");
if(fgets(line,sizeof(line),stdin)==NULL)
Err_quit("No Any data here");
if(strlen(line)<=2)
continue;
alarm=malloc(sizeof(alarm_t));
if(alarm==NULL)
Err_quit("callocate error!\n");
if(sscanf(line,"%d%64[^/n]",&seconds,message)<2)
{
free(alarm);
break;
}
status=pthread_mutex_lock(&alarm_mutex);
if(status!=0)
Err_quit("mutex_lock error!");
memcpy(&alarm->message,message,MAX);
alarm->seconds=seconds;
alarm->times=time(NULL)+seconds;
last=&alarm_list;
next=*last;
while(next!=NULL)
{
if(next->times>=alarm->times)
{
alarm->link=next;
*last=alarm;
break;
}
last=&next->link;
next=next->link;
}
if(next==NULL)
{
*last=alarm;
alarm->link=NULL;
}
for(head=alarm_list;head!=NULL;head=head->link)
{
printf("%ld(%d)[\"%s\"]\n",head->times,head->seconds,head->message );
}
status=pthread_mutex_unlock(&alarm_mutex);
if(status!=0)
Err_quit("mutex_lock error!");
}
return 0;
}
代码2:
#include "unip.h"
/*
mutual exclusing controls muti-alarming requestions;
*/
#define SPIN 10000000
long couters;
/*
this program use trylock_function to tell counters in
*/
time_t end_time;
pthread_mutex_t alarm_mutex=PTHREAD_MUTEX_INITIALIZER;
//header of list must be initialized here,it inited NULL (nothing);
void * threadfunc1(void *arg)
{
int status;
int spin;
while(time(NULL)