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