#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#define SIZE 5
#include <string.h>
#include <time.h>
int out=0,in=0;
int buf[SIZE]={0};
pthread_mutex_t mutex;
sem_t semr,semw;
void *thread_fun(void *avg)
{
while(1)
{
sem_wait(&semr);
pthread_mutex_lock(&mutex);
printf("this characts is %d\n",buf[in]);
in=(in+1)%5;
sleep(1);
pthread_mutex_unlock(&mutex);
sem_post(&semw);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
if(sem_init(&semr,0,0)== -1)
{
perror("sem_init");
return -1;
}
if(sem_init(&semw,0,5)== -1)
{
perror("sem_init");
return -1;
}
if( pthread_mutex_init(&mutex,NULL) ==-1)
{
perror("pthread_mutex_init");
return -1;
}
srand(time(NULL));
int a;
pthread_t tid;
int ret = pthread_create(&tid,NULL,thread_fun,NULL);
if(0 != ret)
{
perror("pthread_create");
return -1;
}
while(1)
{
sem_wait(&semw);
pthread_mutex_lock(&mutex);
a=97+rand()%122;
buf[out]=a;
out=(out+1)%5;
sleep(1);
printf("out=%d\n",buf[out]);
pthread_mutex_unlock(&mutex);
sem_post(&semr);
}
if(0 != pthread_join(tid,NULL))
{
perror("pthread_join");
return -1;
}
03-30
7850