-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsbuf.c
More file actions
34 lines (31 loc) · 773 Bytes
/
Copy pathsbuf.c
File metadata and controls
34 lines (31 loc) · 773 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "sbuf.h"
/* 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;
sp->front = sp->rear = 0;
Sem_init(&sp->mutex, 0, 1);
Sem_init(&sp->slots, 0, n);
Sem_init(&sp->items, 0, 0);
}
/* 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);
P(&sp->mutex);
sp->buf[(++sp->rear) % (sp->n)] = item;
V(&sp->mutex);
V(&sp->items);
}
int sbuf_remove(sbuf_t *sp){
int item;
P(&sp->items);
P(&sp->mutex);
item = sp->buf[(++sp->front) % (sp->n)];
V(&sp->mutex);
V(&sp->slots);
return item;
}