#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<semaphore.h>
typedef struct
{
int value;
sem_t sem,semw;// 信号量要和共享资源相互"绑定"
int sign;
}Storage;
void set_data(Storage *s,int value)
{
s->value=value;
} int get_data(Storage* s)
{
return s->value;
} void* rd1_fn(void *arg)
{
Storage *s=(Storage*)arg;
int i=;
for(;i<;i++)
{
sem_wait(&s->sem);//实现读线程与写线程的同步
s->sign++;
int value=get_data(s);
sleep();
printf("rd1(0x)%lx read data :%d\n",pthread_self(),value);
if(s->sign!=)
sem_post(&s->sem);//实现读线程之间的互斥
else
sem_post(&s->semw);//实现写线程与读线程的同步
// usleep(100);
sleep();
}
return (void*);
}
void* rd2_fn(void *arg)
{
Storage *s=(Storage*)arg;
int i=;
for(;i<;i++)
{
sem_wait(&s->sem);
s->sign++;
int value=get_data(s);
sleep();
printf("rd2(0x)%lx read data :%d\n",pthread_self(),value);
if(s->sign!=)
sem_post(&s->sem);
else
sem_post(&s->semw);
// usleep(100);
sleep();
}
return (void*);
}
void* rd3_fn(void *arg)
{
Storage *s=(Storage*)arg;
int i=;
for(;i<;i++)
{
sem_wait(&s->sem);
s->sign++;
int value=get_data(s);
sleep();
printf("rd3(0x)%lx read data :%d\n",pthread_self(),value);
if(s->sign!=)
sem_post(&s->sem);
else
sem_post(&s->semw);
// usleep(100);
sleep();
}
return (void*);
} void* wt_fn(void *arg)
{
Storage *s=(Storage*)arg;
int i=;
for(;i<;i++)
{
sem_wait(&s->semw);//实现for循环里写线程的互斥
s->sign=;
set_data(s,i+);
sleep();
printf("wt(0x)%lx wrote data :%d\n",pthread_self(),i+);
sem_post(&s->sem);//实现写线程与读线程的同步
sleep();
// sleep(5);
}
return (void*);
}
int main(void)
{
int err;
pthread_t rd1,rd2,rd3,wt;
Storage s;
s.value=;
s.sign=;
sem_init(&s.sem,,);//初始化为0
sem_init(&s.semw,,);//初始化为1
pthread_create(&rd1,NULL,rd1_fn,(void*)&s);
pthread_create(&rd2,NULL,rd2_fn,(void*)&s);
pthread_create(&rd3,NULL,rd3_fn,(void*)&s);
pthread_create(&wt,NULL,wt_fn,(void*)&s);
pthread_join(rd1,NULL);
pthread_join(rd2,NULL);
pthread_join(rd3,NULL);
pthread_join(wt,NULL);
sem_destroy(&s.sem);
sem_destroy(&s.semw);
return ;
}

利用两个信号量 实现了写者之间的互斥,读者之间的互斥,读者和写者之间的同步。 若要实现多个写者,只需按照多个读者的思路写即可。

05-08 15:09