Mercurial > hg > Members > masakoha > testcode
changeset 20:28cac8b199cb
add ppb_queue.h
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Tue, 07 Jan 2014 00:37:27 +0900 |
parents | a9534f217a0c |
children | d137f1823794 |
files | parallel_processing/ppb_cond_queue/ppb_queue.h |
diffstat | 1 files changed, 41 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_cond_queue/ppb_queue.h Tue Jan 07 00:37:27 2014 +0900 @@ -0,0 +1,41 @@ +#ifdef _PPB_QUEUE_H +#define _PPB_QUEUE_H +#include <unistd.h> +#include <pthread.h> + +#ifdef MAX_QUEUE_NUM +#define MAX_QUEUE_NUM 10 +#endif /* MAX_QUEUE_NUM */ + +typedef struct _queue { + int values[MAX_QUEUE_NUM]; + volatile int remain; + int rp, wp; + pthread_mutex_t mutex; + pthread_cond_t not_full; + pthread_cond_t not_empty; +} queue_t; + +void enqueue(queue_t *q, int v) { + pthread_mutex_lock(&q->mutex); + while (q->remain == MAX_QUEUE_NUM) + pthread_cond_wait(&q->not_fill, &q->mutex); + q->values[q->wp] = v; + q->wp++; q->remain++; + if (q->wp == MAX_QUEUE_NUM) q->wp = 0; + pthread_cond_signal(&q->not_empty); + pthread_mutex_unlock(&q->mutex); +} + +void dequeue(queue_t *q, int v) { + pthread_mutex_lock(&q->mutex); + while (q->remain == 0) + pthread_cond_wait(&q->not_empty, &q->mutex); + v = q->values[q->rp]; + q->rp++; q->remain--; + if (q->rp == MAX_QUEUE_NUM) q->rp = 0; + pthread_cond_signal(&q->not_full); + pthread_mutex_unlock(&q->mutex); +} + +#endif /* _PPB_QUEUE_H */