Конспекты

prodcons.c

Код · 95 строк · 3 КБ

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define BUF_SIZE 10
#define ITEMS 30
#define CONSUMERS 3

static int buffer[BUF_SIZE];
static int head = 0;    // откуда читаем
static int tail = 0;    // куда пишем
static int count = 0;   // сколько элементов лежит в буфере
static int done = 0;    // производитель закончил

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;

static long consumed_sum[CONSUMERS];
static int consumed_cnt[CONSUMERS];

static void *producer(void *arg) {
    (void)arg;
    for (int i = 1; i <= ITEMS; i++) {
        pthread_mutex_lock(&mutex);
        while (count == BUF_SIZE) {
            printf("Производитель: буфер полон, жду\n");
            pthread_cond_wait(&not_full, &mutex);
        }
        buffer[tail] = i;
        tail = (tail + 1) % BUF_SIZE;
        count++;
        printf("Производитель: положил %d (в буфере %d)\n", i, count);
        pthread_cond_signal(&not_empty);
        pthread_mutex_unlock(&mutex);
    }
    // Сообщаем, что элементов больше не будет, и будим всех потребителей
    pthread_mutex_lock(&mutex);
    done = 1;
    pthread_cond_broadcast(&not_empty);
    pthread_mutex_unlock(&mutex);
    return NULL;
}

static void *consumer(void *arg) {
    int id = (int)(long)arg;
    for (;;) {
        pthread_mutex_lock(&mutex);
        while (count == 0 && !done)
            pthread_cond_wait(&not_empty, &mutex);
        if (count == 0 && done) {
            pthread_mutex_unlock(&mutex);
            break;
        }
        int item = buffer[head];
        head = (head + 1) % BUF_SIZE;
        count--;
        printf("  Потребитель %d: взял %d (в буфере %d)\n", id, item, count);
        pthread_cond_signal(&not_full);
        pthread_mutex_unlock(&mutex);

        consumed_sum[id - 1] += item;
        consumed_cnt[id - 1]++;
        usleep(20000 * id);   // имитация обработки, потребители разной скорости
    }
    return NULL;
}

int main() {
    pthread_t prod, cons[CONSUMERS];

    pthread_create(&prod, NULL, producer, NULL);
    for (long i = 1; i <= CONSUMERS; i++)
        pthread_create(&cons[i - 1], NULL, consumer, (void *)i);

    pthread_join(prod, NULL);
    for (int i = 0; i < CONSUMERS; i++)
        pthread_join(cons[i], NULL);

    long total = 0;
    int taken = 0;
    for (int i = 0; i < CONSUMERS; i++) {
        printf("Потребитель %d обработал %d элементов\n", i + 1, consumed_cnt[i]);
        total += consumed_sum[i];
        taken += consumed_cnt[i];
    }
    printf("Всего обработано %d из %d, сумма %ld (ожидалась %d)\n",
           taken, ITEMS, total, ITEMS * (ITEMS + 1) / 2);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&not_full);
    pthread_cond_destroy(&not_empty);
    return 0;
}