| 1 | // global variables and procedures shared by all threads.
|
|---|
| 2 |
|
|---|
| 3 | /********************* functions provided by omp.h *************/
|
|---|
| 4 | $input int OMP_NUM_THREADS;
|
|---|
| 5 | int in_barrier[OMP_NUM_THREADS];
|
|---|
| 6 | int num_in_barrier = 0;
|
|---|
| 7 |
|
|---|
| 8 | int omp_get_num_threads() {
|
|---|
| 9 | return OMP_NUM_THREADS;
|
|---|
| 10 | }
|
|---|
| 11 |
|
|---|
| 12 | /********************* helper functions for translation *************/
|
|---|
| 13 |
|
|---|
| 14 | /* Common functions for translating for loops */
|
|---|
| 15 | // computes the start index for a given thread
|
|---|
| 16 | int __for_start(int tid, int total) {
|
|---|
| 17 | return ((total/OMP_NUM_THREADS) * tid);
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | //computes the end index for a given thread
|
|---|
| 21 | int __for_end(int tid, int total) {
|
|---|
| 22 | return ((total/OMP_NUM_THREADS) * (tid + 1));
|
|---|
| 23 | }
|
|---|
| 24 |
|
|---|
| 25 | //computes the extra index for a given thread
|
|---|
| 26 | int __for_extra(int tid, int total) {
|
|---|
| 27 | int offset = total % OMP_NUM_THREADS;
|
|---|
| 28 |
|
|---|
| 29 | if(tid < offset) {
|
|---|
| 30 | return total - offset + tid;
|
|---|
| 31 | }
|
|---|
| 32 | return 0;
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | /********************* barrier implementation *************/
|
|---|
| 36 |
|
|---|
| 37 | void __barrier_init() {
|
|---|
| 38 | for (int i=0; i<OMP_NUM_THREADS; i++) in_barrier[i] = 0;
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | // model the synchronization of threads in the same block
|
|---|
| 42 | void __barrier(int tid) {
|
|---|
| 43 | $atomic {
|
|---|
| 44 | in_barrier[tid] = 1; // I am in the barrier
|
|---|
| 45 | num_in_barrier++; // increment number in barrier
|
|---|
| 46 | if (num_in_barrier == OMP_NUM_THREADS) { // I am last to enter
|
|---|
| 47 | for (int i=0; i<OMP_NUM_THREADS; i++) in_barrier[i] = 0; // release all
|
|---|
| 48 | num_in_barrier = 0; // now none are in barrier
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 | $when (in_barrier[tid] == 0); // wait till I am released
|
|---|
| 52 | }
|
|---|