#define CHECK(_sem) (sem_init(&(_sem)->sem, (pshared), (value)) == 0) ? ((_sem)->valid = true, 0) : ((_sem)->valid = false, -1)
然后使用的地方为
ret = CHECK(_sem)
也就是说,sem_init返回0时,_sem->valid被设置成true, ret被设置为0,
sem_init返回非0时,_sem->valid被设置成false, ret被设置为-1
#include <fcntl.h>#include <semaphore.h>
#include <pthread.h>
#include <sys/stat.h>#define LENTH 8typedef int Ttypedef struct cycle
{
T data[LENTH]
int head
int tail
sem_t *mutex
sem_t *db
int reader
} circularint init_queue(circular *queue)
int is_empty(circular queue)
int is_full(circular queue)
int insert(circular queue, const T data)
int popout(circular queue, T *data)
int queue_lenth(circular queue)
int read_queue(int tag, T *data, circular queue)
int close_queue(circular *queue)int init_queue(circular *queue)
{
queue->head = 0
queue->tail = 0
queue->mutex = sem_open("read", O_RDWR | O_CREAT, 0644, 0)
queue->db = sem_open("write", O_RDWR | O_CREAT, 0644, 0)
sem_init(queue->mutex, 0, 1)
sem_init(queue->db, 0, 1)
queue->reader = 0
return 0
}int is_empty(circular queue)
{
int ret
sem_wait(queue.mutex)
queue.reader++
if(queue.reader == 1)
sem_wait(queue.db)
sem_post(queue.mutex)
//临界区
ret = (queue.head == queue.tail)
//临界区
sem_wait(queue.mutex)
queue.reader--
if(queue.reader == 0)
sem_post(queue.mutex)
return ret
}int is_full(circular queue)
{
int ret
sem_wait(queue.mutex)
queue.reader++
if(queue.reader == 1)
sem_wait(queue.db)
sem_post(queue.mutex)
//临界区
ret = (queue.head == (queue.tail + 1) % LENTH)
//临界区
sem_wait(queue.mutex)
queue.reader--
if(queue.reader == 0)
sem_post(queue.mutex)
return ret
}int insert(circular queue, const T data)
{
int ret = 0
sem_wait(queue.db)
//临界区
if(is_empty(queue))
ret = -1
queue.data[queue.tail] = data
queue.tail = (queue.tail + 1) % LENTH
sem_post(queue.db)
//临界区
return ret
}int popout(circular queue, T *data)
{
int ret = 0
sem_wait(queue.db)
//临界区
if(is_full(queue))
ret = -1
*data = queue.data[queue.head]
queue.head = (queue.head + 1) % LENTH
//临界区
sem_post(queue.db)
return ret
}int queue_lenth(circular queue)
{
int ret
sem_wait(queue.mutex)
queue.reader++
if(queue.reader == 1)
sem_wait(queue.db)
sem_post(queue.mutex)
//临界区
ret = (queue.tail - queue.head + LENTH) % LENTH
//临界区
sem_wait(queue.mutex)
queue.reader--
if(queue.reader == 0)
sem_post(queue.mutex)
return ret
}int read_queue(int tag, T *data, circular queue)
{
int ret = 0
sem_wait(queue.mutex)
queue.reader++
if(queue.reader == 1)
sem_wait(queue.db)
sem_post(queue.mutex)
//临界区
if(tag >= queue_lenth(queue))
ret = -1
*data = queue.data[queue.head + tag]
//临界区
sem_wait(queue.mutex)
queue.reader--
if(queue.reader == 0)
sem_post(queue.mutex)
return ret
}int close_queue(circular *queue)
{
sem_destroy(queue->mutex)
sem_destroy(queue->db)
return 0
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)