Implementation of mutex in child process creation code (fork)

0

Hello

I want to create a mutex to protect the part of the code accesses the pointer to sort the vector.

The intention is to create the same amount of child processes for the number of processors in the machine, and each process orders some of that vector, which has been divided by the number of processors.

   #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <math.h>
    #include <sys/wait.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <time.h>

    int k = 20, pedaco, nNucleo; // K é o tamanho do VETOR RANDOMICO

    int main(void){   

//printf("Qual o numero de nucleos (1, 2, 3 ou 4)? \n");
//scanf("%d", &nNucleo);

nNucleo = sysconf(_SC_NPROCESSORS_ONLN);
//  printf("NUMERO PROCESSADORES E: %d", p);

printf("VETOR PRINCINPAL\n");


int v[20];//CRIA VETOR DE 'K' POSIÇÕES COM INTEIROS RANDOMICOS
int *vetor = v;
srand(time(NULL));

for (int i = 0; i < k; i++)   {
    *(vetor+i) = rand() % k + 1;
        printf("%d ", vetor[i]);
}             

printf("\n-----------------------------------\n");

// DIVIDINDO VETOR
pedaco = (k/nNucleo); // intervalo do vetor dividido vai de: ((nNucleo-1)*pedaco) < (nNucleo*pedaco)

printf("\n-----------------------------------\n");
pid_t childpid;
int num_atual, i, j; 
for (int n = 1; n <= nNucleo; n++){   
    childpid = fork();      
    if (childpid > 0){
        printf("Processo filho %d\n", n); 
        for(i = ((n-1)*pedaco); i < (n*pedaco); i++){
            num_atual = *(vetor +i);
            j=i-1;
                    while((j >= 0) && ((*(vetor +j)) > num_atual)){
                    *(vetor +j+1) = *(vetor+j);
                    j--;
                }
                *(vetor+j+1) = num_atual;
        } 
    }
    else{
        printf("Processo pai %d\n", n);         
        for (int i = 0; i < k; i++){
        printf("vetor[%d] = %d\n", i, vetor[i]);
        }
    }

}

getchar();
return 0;
}
    
asked by anonymous 13.09.2018 / 02:43

0 answers