#include <pthread.h>
#include <semaphore.h>
sem_t full, empty;
int buffer[10];
int in, out;
void* producer(void* arg) {
while (1) {
sem_wait(&empty);
buffer[in] = 1;
in = (in + 1) % 10;
sem_post(&full);
}
}
void* consumer(void* arg) {
while (1) {
sem_wait(&full);
int item = buffer[out];
out = (out + 1) % 10;
sem_post(&empty);
// Process item
}
}
int main() {
pthread_t prod_threads[5], cons_threads[5];
sem_init(&full, 0, 0);
sem_init(&empty, 0, 10);
for (int i = 0; i < 5; i++) {
pthread_create(&prod_threads[i], NULL, producer, NULL);
pthread_create(&cons_threads[i], NULL, consumer, NULL);
}
for (int i = 0; i < 5; i++) {
pthread_join(prod_threads[i], NULL);
pthread_join(cons_threads[i], NULL);
}
return 0;
}