1 #include <stdio.h>
 2 #include <time.h>
 3 #include <stdlib.h>
 4 #include <omp.h>
 5 
 6 // in addmatrix.c
 7 void addmatrix(int ** a, int ** b, int ** c);
 8 
 9 // in printmatrix.c
10 void printmatrix(int ** matrix);
11 
12 // globals
13 int xdim;
14 int ydim;  // matrix dimensions
15 
16 int main(int argc, char * argv[]) {
17 
18   int i,j,n; // loop counters
19 
20   int ** a;  // the matrices themselves
21   int ** b;
22 
23   int count; // number to add
24 
25   // argument stream should be matrix dimensions & count
26   if(argc!=4) {
27     fprintf(stderr,"Usage:\n%s <xdim> <ydim> <count>\n",
28                     argv[0]);
29     exit(1);
30   }
31 
32   xdim = atoi(argv[1]);
33   ydim = atoi(argv[2]);
34   count = atoi(argv[3]);
35 
36   if(xdim <= 0 || ydim <= 0 || count < 2) {
37     fprintf(stderr,"xdim,ydim must be >0, count must be >1\n");
38     exit(1);
39   }
40 
41   // seed the random number generator
42   srand(time(NULL));
43 
44   // allow the omp library to select the number of threads to use
45   omp_set_dynamic(1);
46 
47   // allocate the matrices
48   a = (int **) malloc( ydim * sizeof(int *));
49   b = (int **) malloc( ydim * sizeof(int *));
50 
51   for(j=0;j<ydim;j++) {
52     a[j] = (int*) malloc( xdim * sizeof(int));
53     b[j] = (int*) malloc( xdim * sizeof(int));
54 
55     for(i=0;i<xdim;i++) {
56       a[j][i] = 0;
57       b[j][i] = rand() % 5;
58     }
59   }
60 
61 
62   // do the specified number of additions
63   for(n=0;n<count;n++) {
64 
65     printmatrix(a);
66     fprintf(stdout,"    +\n");
67     printmatrix(b);
68     fprintf(stdout,"    =\n");
69 
70     // calls into an OMP-enabled file    
71     addmatrix(a,a,b); // does a = a+b
72 
73     printmatrix(a);
74     fprintf(stdout,"\n***********************\n\n");
75 
76     // re-initialize b to a new random matrix
77     // Note: this is not done in parallel!
78     for(j=0;j<ydim;j++) {
79       for(i=0;i<xdim;i++) {
80         b[j][i] = rand() % 5;
81       }
82     }
83   }
84 
85   exit(0);
86 }
87