Order guarantee for threads

0

Good evening. I'm running a program that handles 10 threads , but how do I ensure order? type, run from 0 to 9 , since it is now running randomly and I am not able to keep the order. I'll leave the code here:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

#define NUM_THREADS 10

int variavel_compartilhada;
int number;
int next;
int turn[NUM_THREADS] = {0,0,0,0,0,0,0,0,0,0};

void* manipula_variavel(void* param) {
    int indice = (int)param;
        int execucoes = 0;
    printf("THREAD #%d - executando funcao manipula_variavel.\n",indice);   
    while(execucoes<10) {
            execucoes++;
            turn[indice] = __sync_fetch_and_add(&number,1); //protocolo de entrada
            while (turn[indice] != next); //protocolo de entrada            
            //secao critica
            if (indice % 2) {
                variavel_compartilhada += indice;
            } else {
                variavel_compartilhada += (2*indice);
            }
            //secao critica
            printf("THREAD #%d - alterei o valor da variavel para %d\n"
                ,indice,variavel_compartilhada);
            next++; //protocolo de saida
    }
    return 0;
}

int main(void) {
    pthread_t threads[NUM_THREADS];
    int result_create_thread;
    long t = 0;
    variavel_compartilhada = 0;
    number = 0;
    next = 0;
    for(t=0; t<NUM_THREADS; t++){
      printf("main: criando thread %ld\n", t);
      result_create_thread = pthread_create(&threads[t], NULL, manipula_variavel, (void *)t);
      if (result_create_thread){
        printf("ERRO; pthread_create() devolveu o erro %d\n", result_create_thread);
        exit(-1);
      }
    }   
    for(t=0; t<NUM_THREADS; t++) pthread_join(threads[t], NULL); 

    printf("O resultado final para variavel_compartilhada: %d\n",variavel_compartilhada);

    return 0;
}
    
asked by anonymous 01.10.2018 / 04:52

0 answers