#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX 10
int buffer[MAX];
int fill = 0;
int use = 0;
sem_t empty;
sem_t full;
sem_t mutex;
void put(int value) {
buffer[fill] = value;
fill = (fill + 1) % MAX;
}
int get() {
int tmp = buffer[use];
use = (use + 1) % MAX;
return tmp;
}
void* producer(void* arg) {
int loops = *((int*)arg);
for (int i = 0; i < loops; i++) {
sem_wait(&empty);
sem_wait(&mutex);
put(i);
sem_post(&mutex);
sem_post(&full);
}
pthread_exit(NULL);
}
void* consumer(void* arg) {
int loops = *((int*)arg);
for (int i = 0; i < loops; i++) {
sem_wait(&full);
sem_wait(&mutex);
int tmp = get();
sem_post(&mutex);
sem_post(&empty);
printf("%d\n", tmp);
}
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: %s <loops>\n", argv[0]);
return 1;
}
int loops = atoi(argv[1]);
sem_init(&empty, 0, MAX);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
pthread_t prod_thread, cons_thread;
pthread_create(&prod_thread, NULL, producer, &loops);
pthread_create(&cons_thread, NULL, consumer, &loops);
pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}