source: CIVL/examples/pthread/cprover/07_rand_true.c@ 1aaefd4

main test-branch
Last change on this file since 1aaefd4 was ea777aa, checked in by Alex Wilton <awilton@…>, 3 years ago

Moved examples, include, build_default.properties, common.xml, and README out from dev.civl.com into the root of the repo.

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

  • Property mode set to 100644
File size: 1.7 KB
Line 
1//http://www.ibm.com/developerworks/java/library/j-jtp11234/
2//Listing 5. Implementing a thread-safe PRNG with synchronization and atomic variables
3
4#include <pthread.h>
5
6#define assume(e) __VERIFIER_assume(e)
7#define assert(e) { if(!(e)) { ERROR: goto ERROR; (void)0; } }
8
9int m = 0;
10
11void __VERIFIER_atomic_acquire()
12{
13 assume(m==0);
14 m = 1;
15}
16
17void __VERIFIER_atomic_release()
18{
19 assume(m==1);
20 m = 0;
21}
22
23volatile int seed;
24
25inline int PseudoRandomUsingAtomic_nextInt(int n) {
26 int read, nexts, nextInt_return;
27
28 __VERIFIER_atomic_acquire();
29 read = seed;
30
31 do
32 {
33 nexts = __VERIFIER_nondet_int();
34 }
35 while(nexts == read || nexts == 0);
36
37 assert(nexts != read);
38 seed = nexts;
39 __VERIFIER_atomic_release();
40 nextInt_return = nexts % n;
41 //assume(nexts < n + 1);
42 //nextInt_return = nexts;
43
44 return nextInt_return;
45}
46
47inline void PseudoRandomUsingAtomic_monitor(){
48 while(1)
49 {
50 assert(seed != 0);
51 }
52}
53
54inline void PseudoRandomUsingAtomic_constructor(int init){
55 seed = init;
56}
57
58inline void PseudoRandomUsingAtomic__threadmain(){
59 int myrand;
60
61 myrand = PseudoRandomUsingAtomic_nextInt(10);
62 assert(myrand <= 10);
63}
64
65#define STATE_UNINITIALIZED 0
66#define STATE_INITIALIZED 1
67
68volatile int state = STATE_UNINITIALIZED;
69void* thr1(void* arg)
70{
71 __VERIFIER_atomic_acquire();
72 switch(state)
73 {
74 case STATE_UNINITIALIZED:
75 PseudoRandomUsingAtomic_constructor(1);
76 state = STATE_INITIALIZED;
77 __VERIFIER_atomic_release();
78
79 PseudoRandomUsingAtomic_monitor(); //never returns
80 break;
81 case STATE_INITIALIZED:
82 __VERIFIER_atomic_release();
83
84 PseudoRandomUsingAtomic__threadmain();
85 break;
86 }
87
88 return 0;
89}
90
91int main()
92{
93 pthread_t t;
94
95 while(1) { pthread_create(&t, 0, thr1, 0); }
96}
97
Note: See TracBrowser for help on using the repository browser.