/
bvs22
/
draft
Обзор
Документация
Войти
/
bvs22
/
draft
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
threads/reader_writer.c
87 строк
2 KB
Batomunkuev Vladimir
solutions tasks reader and writer
27 ноя 2024, 17:30
27 ноя 2024, 17:30
ebbcc80
Код
Авторство
О чём код?
#include <stdio.h> #include <pthread.h> #include <unistd.h> #define READER_COUNT 5 #define BOOK_SIZE 10 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_reader = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_writer = PTHREAD_COND_INITIALIZER; int book[BOOK_SIZE] = {0}; int written = 0; int active_readers = 0; int active_writers = 0; void* reader_func(void* arg) { int reader_id = *(int*)arg; for (int i = 0; i < BOOK_SIZE; i++) { pthread_mutex_lock(&mutex); while(active_writers || written <= i) { pthread_cond_wait(&cond_reader, &mutex); } active_readers++; printf("Прочитано читателем %d: %d\n", reader_id, book[i]); fflush(stdout); active_readers--; if(active_readers == 0) { pthread_cond_signal(&cond_writer); } pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } void* writer_func(void* arg) { for (int i = 0; i < BOOK_SIZE; i++) { pthread_mutex_lock(&mutex); while(active_readers > 0) { pthread_cond_wait(&cond_writer, &mutex); } active_writers++; book[i] = i; written++; printf("Произведено: %d\n", book[i]); fflush(stdout); active_writers = 0; pthread_cond_broadcast(&cond_reader); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(NULL); } int main() { pthread_t reader[READER_COUNT], writer; int reader_id[READER_COUNT] = {0}; pthread_create(&writer, NULL, writer_func, NULL); for(int i = 0; i < READER_COUNT; i++) { reader_id[i] = i + 1; pthread_create(&reader[i], NULL, reader_func, &reader_id[i]); } for(int i = 0; i < READER_COUNT; i++) { pthread_join(reader[i], NULL); } pthread_join(writer, NULL); printf("\n"); return 0; }