source: CIVL/examples/translation/pthread/stack_false.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: 1.6 KB
Line 
1#include <pthread.h>
2#include <stdio.h>
3#include <stdlib.h>
4
5#define TRUE (1)
6#define FALSE (0)
7#define SIZE (5)
8#define OVERFLOW (-1)
9#define UNDERFLOW (-2)
10
11static int top=0;
12static unsigned int arr[SIZE];
13pthread_mutex_t m;
14_Bool flag=FALSE;
15
16unsigned int unsignednondet(void)
17{
18 if (((double) rand() / (RAND_MAX+1.0)) > 0.5)
19 return 1;
20 return 0;
21}
22
23void error(void)
24{
25 ERROR: ;
26 goto ERROR;
27 return;
28}
29
30void inc_top(void)
31{
32 top++;
33}
34
35void dec_top(void)
36{
37 top--;
38}
39
40int get_top(void)
41{
42 return top;
43}
44
45int stack_empty(void)
46{
47 (top==0) ? TRUE : FALSE;
48}
49
50int push(unsigned int *stack, int x)
51{
52 if (top==SIZE)
53 {
54 printf("stack overflow\n");
55 return OVERFLOW;
56 }
57 else
58 {
59 stack[get_top()] = x;
60 inc_top();
61 }
62 return 0;
63}
64
65int pop(unsigned int *stack)
66{
67 if (get_top()==0)
68 {
69 printf("stack underflow\n");
70 return UNDERFLOW;
71 }
72 else
73 {
74 dec_top();
75 return stack[get_top()];
76 }
77 return 0;
78}
79
80void *t1(void *arg)
81{
82 int i;
83 unsigned int tmp;
84
85 for(i=0; i<SIZE; i++)
86 {
87 pthread_mutex_lock(&m);
88 tmp = unsignednondet()%SIZE;
89 if (push(arr,tmp)==OVERFLOW)
90 error();
91 flag=TRUE;
92 pthread_mutex_unlock(&m);
93 }
94}
95
96void *t2(void *arg)
97{
98 int i;
99
100 for(i=0; i<SIZE; i++)
101 {
102 pthread_mutex_lock(&m);
103 if (flag)
104 {
105 if (!(pop(arr)!=UNDERFLOW))
106 error();
107 }
108 pthread_mutex_unlock(&m);
109 }
110}
111
112
113int main(void)
114{
115 pthread_t id1, id2;
116
117 pthread_mutex_init(&m, 0);
118
119 pthread_create(&id1, NULL, t1, NULL);
120 pthread_create(&id2, NULL, t2, NULL);
121
122 pthread_join(id1, NULL);
123 pthread_join(id2, NULL);
124
125 return 0;
126}
127
128
Note: See TracBrowser for help on using the repository browser.