comparison parallel_processing/ppb_cond_queue/ppb_queue.h @ 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
children d137f1823794
comparison
equal deleted inserted replaced
19:a9534f217a0c 20:28cac8b199cb
1 #ifdef _PPB_QUEUE_H
2 #define _PPB_QUEUE_H
3 #include <unistd.h>
4 #include <pthread.h>
5
6 #ifdef MAX_QUEUE_NUM
7 #define MAX_QUEUE_NUM 10
8 #endif /* MAX_QUEUE_NUM */
9
10 typedef struct _queue {
11 int values[MAX_QUEUE_NUM];
12 volatile int remain;
13 int rp, wp;
14 pthread_mutex_t mutex;
15 pthread_cond_t not_full;
16 pthread_cond_t not_empty;
17 } queue_t;
18
19 void enqueue(queue_t *q, int v) {
20 pthread_mutex_lock(&q->mutex);
21 while (q->remain == MAX_QUEUE_NUM)
22 pthread_cond_wait(&q->not_fill, &q->mutex);
23 q->values[q->wp] = v;
24 q->wp++; q->remain++;
25 if (q->wp == MAX_QUEUE_NUM) q->wp = 0;
26 pthread_cond_signal(&q->not_empty);
27 pthread_mutex_unlock(&q->mutex);
28 }
29
30 void dequeue(queue_t *q, int v) {
31 pthread_mutex_lock(&q->mutex);
32 while (q->remain == 0)
33 pthread_cond_wait(&q->not_empty, &q->mutex);
34 v = q->values[q->rp];
35 q->rp++; q->remain--;
36 if (q->rp == MAX_QUEUE_NUM) q->rp = 0;
37 pthread_cond_signal(&q->not_full);
38 pthread_mutex_unlock(&q->mutex);
39 }
40
41 #endif /* _PPB_QUEUE_H */