comparison parallel_processing/chapter3/ppb_cond_queue/ppb_queue.h @ 22:508b47c8f4d8

package Chapter3
author Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp>
date Tue, 07 Jan 2014 14:30:28 +0900
parents parallel_processing/ppb_cond_queue/ppb_queue.h@d137f1823794
children
comparison
equal deleted inserted replaced
21:d137f1823794 22:508b47c8f4d8
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 /*
11 typedef struct _queue {
12 int values[MAX_QUEUE_NUM];
13 volatile int remain;
14 int rp, wp;
15 pthread_mutex_t mutex;
16 pthread_cond_t not_full;
17 pthread_cond_t not_empty;
18 } queue_t;
19 */
20
21 void enqueue(queue_t *q, int v) {
22 pthread_mutex_lock(&q->mutex);
23 while (q->remain == MAX_QUEUE_NUM)
24 pthread_cond_wait(&q->not_full, &q->mutex);
25 q->values[q->wp] = v;
26 q->wp++; q->remain++;
27 if (q->wp == MAX_QUEUE_NUM) q->wp = 0;
28 pthread_cond_signal(&q->not_empty);
29 pthread_mutex_unlock(&q->mutex);
30 }
31
32 void dequeue(queue_t *q, int v) {
33 pthread_mutex_lock(&q->mutex);
34 while (q->remain == 0)
35 pthread_cond_wait(&q->not_empty, &q->mutex);
36 v = q->values[q->rp];
37 q->rp++; q->remain--;
38 if (q->rp == MAX_QUEUE_NUM) q->rp = 0;
39 pthread_cond_signal(&q->not_full);
40 pthread_mutex_unlock(&q->mutex);
41 }
42
43 #endif /* _PPB_QUEUE_H */