1.23
2.0
main
test-branch
| 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 | */
|
|---|
| 5 | #include<civlc.h>
|
|---|
| 6 |
|
|---|
| 7 | $input int B; // upper bound on array length
|
|---|
| 8 | $input int W; // upper bound on number of workers
|
|---|
| 9 |
|
|---|
| 10 | $input int N; // array length
|
|---|
| 11 | $assume N>=1 && N<=B;
|
|---|
| 12 | $input int P; // number of workers
|
|---|
| 13 | $assume P>=1 && P<=W;
|
|---|
| 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 |
|
|---|
| [8b354468] | 34 | $atomic {
|
|---|
| 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 | }
|
|---|
| 48 | $atomic {
|
|---|
| 49 | for (int i=0; i<P; i++)
|
|---|
| [a82987f] | 50 | $wait(workers[i]);
|
|---|
| [2fa36af] | 51 | }
|
|---|
| [72c01cc] | 52 | return result;
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
| 55 | void main() {
|
|---|
| 56 | double sum_seq = adder_seq();
|
|---|
| 57 | double sum_par = adder_par();
|
|---|
| 58 |
|
|---|
| [09b9231b] | 59 | $assert(sum_seq == sum_par);
|
|---|
| [72c01cc] | 60 | }
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.