#include "csapp.h"
typedef struct {
int *buf; /* Buffer array */
int n; /* Maximum number of slots */
int front; /* buf[(front+1)%n] is first item */
int rear; /* buf[rear%n] is last item */
sem_t mutex; /* Protects accesses to buf */
sem_t slots; /* Counts available slots */
sem_t items; /* Counts available items */
} sbuf_t;
void P(sem_t *s); /* Wrapper function for sem_wait */
void V(sem_t *s); /* Wrapper function for sem_post */
/* Create an empty, bounded, shared FIFO buffer with n slots */
void sbuf_init(sbuf_t *sp, int n)
{
sp->buf = Calloc(n, sizeof(int));
sp->n = n; /* Buffer holds max of n items */
sp->front = sp->rear = 0; /* Empty buffer iff front == rear */
Sem_init(&sp->mutex, 0, 1); /* Binary semaphore for locking */
Sem_init(&sp->slots, 0, n); /* Initially, buf has n empty slots */
Sem_init(&sp->items, 0, 0); /* Initially, buf has zero data items */
}
/* Clean up buffer sp */
void sbuf_deinit(sbuf_t *sp)
{
Free(sp->buf);
}
/* Insert item onto the rear of shared buffer sp */
void sbuf_insert(sbuf_t *sp, int item)
{
P(&sp->slots); /* Wait for available slot */
P(&sp->mutex); /* Lock the buffer */
sp->buf[(++sp->rear)%(sp->n)] = item; /* Insert the item */
V(&sp->mutex); /* Unlock the buffer */
V(&sp->items); /* Announce available item */
}
/* Remove and return the first item from buffer sp */
int sbuf_remove(sbuf_t *sp)
{
int item;
P(&sp->items); /* Wait for available item */
P(&sp->mutex); /* Lock the buffer */
item = sp->buf[(++sp->front)%(sp->n)]; /* Remove the item */
V(&sp->mutex); /* Unlock the buffer */
V(&sp->slots); /* Announce available slot */
return item;
}
< /code>
Практическая задача 12.9
let p обозначает количество производителей, c количество потребителей и n размер буфера
в единицах элементов. Для каждого из следующих сценариев укажите, необходимо ли
semaphore mutex в sbuf_insert и sbuf_remove или нет.
a. p = 1, c = 1, n> 1 < /p>
Ответ
a. p = 1, c = 1, n> 1: Да, семафор мутекс необходим, потому что
производитель и потребитель могут одновременно получить доступ к буферу. Это то, что производитель и потребитель могут получить доступ к одному и тому же индексу? Или не так, что даже если они этого не делают, доступ к массиву все еще требует взаимного исключения?>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ess-differ
CSAPP 12.9 Упражнение, почему мутекс необходим? Разве это не нормально, если мы получаем доступ к разным позициям в буфе ⇐ C++
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
CSAPP самостоятельное обучение Attack Lab Phase 1 Невозможно ввести строку
Anonymous » » в форуме Linux - 0 Ответы
- 65 Просмотры
-
Последнее сообщение Anonymous
-
-
-
(киномашина) Попытка переместить гусеничную тележку по позициям пути при нажатии клавиши.
Anonymous » » в форуме C# - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-