#include #include #include #include #include #define N 100 // Definition of the Q typedef struct Q { int* q; int pos; } Q; // Create a Q of integers that are the work items. struct Q* initQ(int n) { int i; struct Q *newQ = (struct Q *) malloc(sizeof(Q)); newQ->q = (int*) malloc(sizeof(int)*n); newQ->pos = n-1; for (int i = 0; i < n; i++) { if (rand( ) < 200000000) newQ->q[i] = 1; else newQ->q[i] = 0; } return newQ; } void doWork(int s) { sleep(s); } int getWork(struct Q* workQ) { int w; #pragma omp critical { if (workQ->pos > -1) { w = workQ->q[workQ->pos]; workQ->pos--; } else { w = -1; } } // end of critical return w; } int main (int argc, char *argv[]) { Q* q = initQ(N); int w = getWork(q); double t = omp_get_wtime( ); while (w > -1) { doWork(w); w = getWork(q); } t = omp_get_wtime( ) - t; printf("time for sequential processing is %f\n", t); q->pos = N-1; w = getWork(q); t = omp_get_wtime( ); #pragma omp parallel { #pragma omp sections { #pragma omp section { while (w > -1) { doWork(w); w = getWork(q); } } // end parallel section #pragma omp section { while (w > -1) { doWork(w); w = getWork(q); } } // end parallel section #pragma omp section { while (w > -1) { doWork(w); w = getWork(q); } } // end parallel section #pragma omp section { while (w > -1) { doWork(w); w = getWork(q); } } // end section } // end sections } // end parallel t = omp_get_wtime( ) - t; printf("time for parallel processing is %f\n", t); }