/
bvs22
/
draft
Обзор
Документация
Войти
/
bvs22
/
draft
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
threads/queue_tasks.c
130 строк
3 KB
bvs22
queue tasks used pthread
01 дек 2024, 09:53
01 дек 2024, 09:53
11254ca
Код
Авторство
О чём код?
#include <stdio.h> #include <pthread.h> #include <unistd.h> #define SIZE_PRODUCER 5 #define SIZE_CONSUMER 5 #define SIZE_STORAGE 5 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_count = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int storage[SIZE_STORAGE] = {0}; int count = 0; void print_storage(void) { for (int i = 0; i < SIZE_STORAGE; i++) { printf("[%d] ", storage[i]); } printf("\n\n"); fflush(stdout); } void *producer_func(void *args) { int id_producer = *(int*)args; while (1) { if (count < SIZE_STORAGE) { pthread_mutex_lock(&mutex); storage[count] = 1; printf("Производитель %d положил товар в ячейку %d\n", id_producer, count + 1); print_storage(); count++; pthread_mutex_unlock(&mutex); sleep(1); } else { pthread_mutex_lock(&mutex_count); while(count == SIZE_STORAGE) { pthread_cond_wait(&cond, &mutex_count); } pthread_mutex_unlock(&mutex_count); } } pthread_exit(NULL); } void *consumer_func(void *args) { int id_consumer = *(int*)args; while(1) { if (count != 0) { pthread_mutex_lock(&mutex); printf("Потребитель %d забрал товар из первой ячейки\n", id_consumer); for (int i = 0; i < count; i++) { storage[i] = storage[i + 1]; } storage[count - 1] = 0; print_storage(); count--; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); sleep(3); } else { pthread_mutex_lock(&mutex_count); while(count == 0) { pthread_cond_wait(&cond, &mutex_count); } pthread_mutex_unlock(&mutex_count); } } pthread_exit(NULL); } int main() { pthread_t producer[SIZE_PRODUCER], consumer[SIZE_CONSUMER]; int id_producer[SIZE_PRODUCER] = {0}; int id_consumer[SIZE_CONSUMER] = {0}; int ret = 0; for (int i = 0; i < SIZE_PRODUCER; i++) { id_consumer[i] = i + 1; id_producer[i] = i + 1; ret =pthread_create(&producer[i], NULL, producer_func, (void*)&id_producer[i]); if (ret != 0) { printf("Ошибка создания потока производителя %d\n", i); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex_count); pthread_cond_destroy(&cond); return 1; } ret = pthread_create(&consumer[i], NULL, consumer_func, (void*)&id_consumer[i]); if (ret != 0) { printf("Ошибка создания потока потребителя %d\n", i); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex_count); pthread_cond_destroy(&cond); return 1; } } for (int i = 0; i < SIZE_PRODUCER; i++) { pthread_join(producer[i], NULL); pthread_join(consumer[i], NULL); } return 0; }