/*************************************************************************
> File Name: producerAndconsumer.c
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: Wed 18 Feb 2015 11:22:02 AM WST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 16
char buffer[N];
int product;
sem_t sem_mutex;
sem_t sem_full;
sem_t sem_empty;
void *producer(void *arg) {
static int index;
while(1) {
sem_wait(&sem_empty);
sem_wait(&sem_mutex);
buffer[index] = product;
product++;
index = (index + 1) & (N - 1);
sem_post(&sem_mutex);
sem_post(&sem_full);
sleep(1);
}
}
void *consumer(void *arg) {
static int index;
while(1) {
sem_wait(&sem_full);
sem_wait(&sem_mutex);
printf("%d\n", buffer[index]);
index = (index + 1) & (N - 1);
sem_post(&sem_mutex);
sem_post(&sem_empty);
sleep(1);
}
}
int main() {
pthread_t pid_p, pid_c;
sem_init(&sem_mutex, 0, 1);
sem_init(&sem_full, 0, 0);
sem_init(&sem_empty, 0, N);
if(pthread_create(&pid_p, NULL, producer, NULL)) {
perror("producer thread creating failed...!\n");
exit(EXIT_FAILURE);
}
if(pthread_create(&pid_p, NULL, consumer, NULL)) {
perror("consumer thread creating failed...!\n");
exit(EXIT_FAILURE);
}
pthread_join(pid_p, NULL);
pthread_join(pid_c, NULL);
// sem_destory(&sem_mutex);
// sem_destory(&sem_full);
// sem_destory(&sem_empty);
return 0;
}