retsohuang
10/20/2015 - 12:18 PM

Sort with openMp

Sort with openMp

/******************************************************************************
* FILE: omp_hello.c
* DESCRIPTION:
*   OpenMP Example - Hello World - C/C++ Version
*   In this simple example, the master thread forks a parallel region.
*   All threads in the team obtain their unique thread number and print it.
*   The master thread only prints the total number of threads.  Two OpenMP
*   library routines are used to obtain the number of threads and each
*   thread's number.
* AUTHOR: Blaise Barney  5/99
* LAST REVISED: 04/06/05
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXX 10 
#define MAXY 8 

int matrix[MAXX][MAXY];

void init_array();
void print_array();
void bs(int *vetor, int n);


int main (int argc, char *argv[]){
    int nthreads, tid;
    int i, j;
    init_array();

    /* Fork a team of threads giving them their own copies of variables */
    #pragma omp parallel private(nthreads, tid, i, j) num_threads(4)
    {
        /* Obtain thread number */
        tid = omp_get_thread_num();
        nthreads = omp_get_num_threads();
        #pragma omp for schedule(static, MAXX/nthreads)
        for(i=0; i<MAXX; i++){
            printf("Thread=%d did row=%d\n", tid, i);
            bs(matrix[i], MAXY);
        }

    }  /* All threads join master thread and disband */

    print_array();

}

void init_array(){
    long i, j;
    srand(time(NULL));
    for(i=0; i < MAXX; i++){
        for(j=0; j < MAXY; j++){
            matrix[i][j] = 1 + (rand() % 100); /* set element at location i to i + 100 */
        }
    }
}

void print_array(){
    int h, k;
    for(k=0; k<MAXX; k++){
        printf("\n");
        for(h=0; h<MAXY; h++){
            printf("%d, ", matrix[k][h]);
        }
    }
    printf("\n");
}

void bs(int * vetor, int n){
    int c=0, d, troca, trocou =1;

    while (c < (n-1) & trocou ){
        trocou = 0;
        for (d = 0 ; d < n - c - 1; d++)
            if (vetor[d] > vetor[d+1])
            {
                troca      = vetor[d];
                vetor[d]   = vetor[d+1];
                vetor[d+1] = troca;
                trocou = 1;
            }
        c++;
    }
}