Untitled

 avatar
unknown
plain_text
10 months ago
1.2 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>

#define MAX_ITEMS 26 // A-Z

sem_t empty, full;
int buffer = 0;
int in = 0, out = 0;

void *producer(void *args) {
    for (char c = 'A'; c <= 'Z'; c++) {
        sem_wait(&empty); // המתן עד שיהיה מקום פנוי בחוצץ
        buffer = c; // הכנס את התו לחוצץ
        printf("Producer wrote: %c\n", c);
        sem_post(&full); // העירו את הצרכן
    }
    return NULL;
}

void *consumer(void *args) {
    char c;
    for (int i = 0; i < MAX_ITEMS; i++) {
        sem_wait(&full); // המתן עד שיהיה פריט בחוצץ
        c = buffer;
        printf("Consumer read: %c\n", c);
        sem_post(&empty); // העירו את היצרן
    }
    return NULL;
}

int main() {
    pthread_t prod, cons;
    sem_init(&empty, 0, MAX_ITEMS); // מקום פנוי בחוצץ
    sem_init(&full, 0, 0); // חוצץ ריק בהתחלה

    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);

    pthread_join(prod, NULL);
    pthread_join(cons, NULL);

    sem_destroy(&empty);
    sem_destroy(&full);

    return 0;
}
Editor is loading...
Leave a Comment