source: CIVL/examples/translation/pthread/queue_ok_true.cvl@ be4355b

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