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

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

added comments to pthread examples.

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

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