source: CIVL/examples/translation/pthread/queue_false.c@ 2e6fe6f

1.23 2.0 main test-branch
Last change on this file since 2e6fe6f was 1746c5c, checked in by John Edenhofner <johneden@…>, 12 years ago

Modified header files and fixed Ticket 218

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@1190 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 2.2 KB
Line 
1#include <pthread.h>
2#include <stdio.h>
3#include <assert.h>
4
5#define SIZE (5)
6#define EMPTY (-1)
7#define FULL (-2)
8#define FALSE (0)
9#define TRUE (1)
10
11typedef struct {
12 int element[SIZE];
13 int head;
14 int tail;
15 int amount;
16} QType;
17
18pthread_mutex_t m;
19int stored_elements[SIZE];
20_Bool enqueue_flag, dequeue_flag;
21QType queue;
22
23int init(QType *q)
24{
25 q->head=0;
26 q->tail=0;
27 q->amount=0;
28 return 0;
29}
30
31int empty(QType * q)
32{
33 if (q->head == q->tail)
34 {
35 printf("queue is empty\n");
36 return EMPTY;
37 }
38 else
39 return 0;
40}
41
42int full(QType * q)
43{
44 if (q->amount == SIZE)
45 {
46 printf("queue is full\n");
47 return FULL;
48 }
49 else
50 return 0;
51}
52
53int enqueue(QType *q, int x)
54{
55 q->element[q->tail] = x;
56 q->amount++;
57 if (q->tail == SIZE)
58 {
59 q->tail = 1;
60 }
61 else
62 {
63 q->tail++;
64 }
65
66 return 0;
67}
68
69int dequeue(QType *q)
70{
71 int x;
72
73 x = q->element[q->head];
74 q->amount--;
75 if (q->head == SIZE)
76 {
77 q->head = 1;
78 }
79 else
80 q->head++;
81
82 return x;
83}
84
85void *t1(void *arg)
86{
87 int value, i;
88
89 pthread_mutex_lock(&m);
90 value = 1;
91 if (enqueue(&queue,value)) {
92 goto ERROR;
93 }
94
95 stored_elements[0]=value;
96 if (empty(&queue)) {
97 goto ERROR;
98 }
99
100 pthread_mutex_unlock(&m);
101
102 for(i=0; i<(SIZE-1); i++)
103 {
104 pthread_mutex_lock(&m);
105 if (enqueue_flag)
106 {
107 value = 1;
108 enqueue(&queue,value);
109 stored_elements[i+1]=value;
110 enqueue_flag=FALSE;
111 dequeue_flag=TRUE;
112 }
113 pthread_mutex_unlock(&m);
114 }
115
116 return NULL;
117
118 ERROR:
119 printf("!");
120 goto ERROR;
121}
122
123void *t2(void *arg)
124{
125 int i;
126
127 for(i=0; i<SIZE; i++)
128 {
129 pthread_mutex_lock(&m);
130 if (dequeue_flag)
131 {
132 if (!dequeue(&queue)==stored_elements[i]) {
133 printf("!");
134 ERROR:
135 goto ERROR;
136 }
137 dequeue_flag=FALSE;
138 enqueue_flag=TRUE;
139 }
140 pthread_mutex_unlock(&m);
141 }
142
143 return NULL;
144}
145
146int main(void)
147{
148 pthread_t id1, id2;
149
150 enqueue_flag=TRUE;
151 dequeue_flag=FALSE;
152
153 init(&queue);
154
155 if (!empty(&queue)==EMPTY) {
156 ERROR:
157 goto ERROR;
158 }
159
160
161 pthread_mutex_init(&m, 0);
162
163 pthread_create(&id1, NULL, t1, &queue);
164 pthread_create(&id2, NULL, t2, &queue);
165
166 pthread_join(id1, NULL);
167 pthread_join(id2, NULL);
168
169 return 0;
170}
171
Note: See TracBrowser for help on using the repository browser.