source:
CIVL/examples/concurrency/blockAdder.cvl
| Last change on this file was ea777aa, checked in by , 3 years ago | |
|---|---|
|
|
| File size: 1.2 KB | |
| Rev | Line | |
|---|---|---|
| [72c01cc] | 1 | /* Compare sequential and parallel sum of array by block partition |
| 2 | * Example run: | |
| [9fb69d3] | 3 | * civl verify -inputB=6 -inputW=3 blockAdder.cvl |
| [72c01cc] | 4 | */ |
| [e6b02c8] | 5 | #include<civlc.cvh> |
| [72c01cc] | 6 | |
| [0baeebd] | 7 | $input int B = 6; // upper bound on array length |
| 8 | $input int W = 3; // upper bound on number of workers | |
| [72c01cc] | 9 | |
| 10 | $input int N; // array length | |
| [3ff27cf] | 11 | $assume(N>=1 && N<=B); |
| [72c01cc] | 12 | $input int P; // number of workers |
| [3ff27cf] | 13 | $assume(P>=1 && P<=W); |
| [72c01cc] | 14 | $input double a[N]; |
| 15 | ||
| 16 | double adder_seq() { | |
| 17 | double s = 0.0; | |
| 18 | ||
| 19 | for (int i=0; i<N; i++) | |
| 20 | s += a[i]; | |
| 21 | return s; | |
| 22 | } | |
| 23 | ||
| 24 | double adder_par() { | |
| 25 | $proc workers[P]; // the workers | |
| 26 | int lock = 0; // lock for accessing result | |
| 27 | double result = 0.0; // shared by all workers | |
| 28 | ||
| 29 | void run_worker(int id) { | |
| 30 | int start = (id*N)/P; | |
| 31 | int stop = ((id+1)*N)/P; | |
| 32 | double localSum = 0.0; | |
| 33 | ||
| [7b92a9d] | 34 | $atomic { |
| [8b354468] | 35 | for (int i=start; i<stop; i++) |
| 36 | localSum += a[i]; | |
| 37 | } | |
| [b50c660] | 38 | $when (lock==0) lock = 1; |
| 39 | result += localSum; | |
| 40 | lock = 0; | |
| [72c01cc] | 41 | } |
| 42 | ||
| [8b354468] | 43 | $atomic { |
| 44 | for (int i=0; i<P; i++) ; // hack | |
| 45 | for (int i=0; i<P; i++) | |
| 46 | workers[i] = $spawn run_worker(i); | |
| 47 | } | |
| [3ff27cf] | 48 | $waitall(workers, P); |
| [72c01cc] | 49 | return result; |
| 50 | } | |
| 51 | ||
| 52 | void main() { | |
| 53 | double sum_seq = adder_seq(); | |
| 54 | double sum_par = adder_par(); | |
| 55 | ||
| [3ff27cf] | 56 | $assert((sum_seq == sum_par)); |
| [72c01cc] | 57 | } |
Note:
See TracBrowser
for help on using the repository browser.
