#include #include #define MAX 1000 struct fila { int v[MAX]; int head, tail; sem_t full, empty, mutex; }; /************************ Buffer circular ************************/ void init(struct fila *f) { f->head = 0; f->tail = 0; } void add(struct fila *f, int n) { f->v[f->head] = n; f->head++; if(f->head >= MAX) f->head = 0; } int delete(struct fila *f) { int n = f->v[f->tail]; f->tail++; if(f->tail >= MAX) f->tail = 0; return n; } /***************************** Fila *****************************/ struct fila *criar_fila() { struct fila *f; int id = shmget(IPC_PRIVATE, sizeof(struct fila), IPC_CREAT|0660); if(id < 0) { perror("shmget falhou."); exit(1); } f = shmat(id, NULL, 0); if(f < 0) { perror("shmat falhou."); exit(1); } sem_init(&f->mutex, 0, 1); sem_init(&f->empty, 0, 0); sem_init(&f->full, 0, MAX); init(f); return f; } int tirar_fila(struct fila *f) { sem_wait(&f->empty); sem_wait(&f->mutex); int n = delete(f); sem_post(&f->mutex); sem_post(&f->full); return n; } void por_fila(struct fila *f, int elem) { sem_wait(&f->full); sem_wait(&f->mutex); add(f, elem); sem_post(&f->mutex); sem_post(&f->empty); }