source: CIVL/examples/translation/pthread/queue_ok_true.c@ bfebb46

1.23 2.0 main test-branch
Last change on this file since bfebb46 was 5fb1a47, checked in by Manchun Zheng <zmanchun@…>, 12 years ago

added pthread examples

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

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