source:
CIVL/examples/concurrency/adder.cvl@
4f22a92
| Last change on this file since 4f22a92 was 8b354468, checked in by , 12 years ago | |
|---|---|
|
|
| File size: 951 bytes | |
| Rev | Line | |
|---|---|---|
| [24ca21c] | 1 | /* |
| 2 | * civl verify -inputB=5 adder.cvl | |
| 3 | * */ | |
| [f28d814] | 4 | #include <civlc.h> |
| [844ebd8] | 5 | |
| [72c01cc] | 6 | $input int B; // upper bound on array length |
| 7 | $input int N; // length of array | |
| 8 | $assume 0<=N && N<=B; | |
| 9 | $input double a[N]; | |
| 10 | ||
| 11 | double adderSeq(double *p, int n) { | |
| [844ebd8] | 12 | double s = 0.0; |
| 13 | ||
| [24ca21c] | 14 | $atomic{ |
| [8b354468] | 15 | for (int i = 0; i < n; i++) { |
| 16 | s += p[i]; | |
| 17 | } | |
| 18 | } | |
| [844ebd8] | 19 | return s; |
| 20 | } | |
| 21 | ||
| [72c01cc] | 22 | double adderPar(double *p, int n) { |
| 23 | double s = 0.0; // sum shared by workers | |
| 24 | int mutex = 0; // mutex shared by workers | |
| 25 | $proc workers[n]; // one worker for each element! | |
| [5b49b89] | 26 | |
| [844ebd8] | 27 | void worker(int i) { |
| [5b49b89] | 28 | double t; |
| 29 | ||
| [8b354468] | 30 | $atomic { |
| 31 | $when (mutex == 0) mutex = 1; | |
| 32 | t = s; | |
| 33 | t += p[i]; | |
| 34 | s = t; | |
| 35 | mutex = 0; | |
| 36 | } | |
| [844ebd8] | 37 | } |
| 38 | ||
| [8b354468] | 39 | $atomic { |
| 40 | for (int j = 0; j < n; j++) | |
| 41 | workers[j] = $spawn worker(j); | |
| 42 | } | |
| [24ca21c] | 43 | |
| [8b354468] | 44 | $atomic { |
| 45 | for (int j = 0; j < n; j++) | |
| 46 | $wait workers[j]; | |
| 47 | } | |
| [844ebd8] | 48 | return s; |
| 49 | } | |
| 50 | ||
| 51 | void main() { | |
| [72c01cc] | 52 | double seq = adderSeq(&a[0], N); |
| 53 | double par = adderPar(&a[0], N); | |
| 54 | ||
| [f28d814] | 55 | $assert seq == par; |
| [844ebd8] | 56 | } |
Note:
See TracBrowser
for help on using the repository browser.
