Untitled

 avatar
unknown
c_cpp
a month ago
3.0 kB
4
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

int *buffer;
int mutex = 1, full = 0, empty, buffer_size, x = 0;

void producer(int);
void consumer(int);
int wait(int);
int signal(int);
void display_status();

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int main() {
    int choice, items;

    printf("Enter the size of the buffer: ");
    scanf("%d", &buffer_size);
    empty = buffer_size;

    buffer = (int*)malloc(sizeof(int) * buffer_size);

    if (buffer == NULL) {
        printf("Memory allocation failed!\n");
        return -1;
    }

    printf("\n1. Producer\n2. Consumer\n3. Exit\n");
    while (1) {
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                if ((mutex == 1) && (empty != 0)) {
                    printf("Enter number of items to produce: ");
                    scanf("%d", &items);
                    if (items > empty) {
                        printf("Not enough empty slots available. Try producing fewer items.\n");
                    } else {
                        producer(items);
                    }
                } else {
                    printf("Buffer is full\n");
                }
                break;
            case 2:
                if ((mutex == 1) && (full != 0)) {
                    printf("Enter number of items to consume: ");
                    scanf("%d", &items);
                    if (items > full) {
                        printf("Not enough full items to consume. Try consuming fewer items.\n");
                    } else {
                        consumer(items);
                    }
                } else {
                    printf("Buffer is empty\n");
                }
                break;
            case 3:
                free(buffer);
                return 0;
            default:
                printf("Invalid choice\n");
                break;
        }
    }
    return 0;
}

int wait(int s) {
    return (--s);
}

int signal(int s) {
    return (++s);
}

void producer(int n) {
    pthread_mutex_lock(&lock);
    
    full = signal(full);
    empty = wait(empty);

    for (int i = 0; i < n; i++) {
        buffer[full - 1] = x + 1;
        printf("Producer produces item %d\n", x + 1);
        x++;
        sleep(rand() % 2);
    }
    
    display_status();
    
    pthread_mutex_unlock(&lock);
}

void consumer(int n) {
    pthread_mutex_lock(&lock);

    full = wait(full);
    empty = signal(empty);

    for (int i = 0; i < n; i++) {
        printf("Consumer consumes item %d\n", buffer[full]);
        x--;
        sleep(rand() % 2);
    }
    
    display_status();
    
    pthread_mutex_unlock(&lock);
}

void display_status() {
    printf("Buffer status: Full = %d, Empty = %d\n", full, empty);
}
Leave a Comment