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