Different behaviors between Linux and Windows using threads (pthreads)

3

I'm using the linux pthreads library to try the threads features, the code below prints 5 messages on the screen for each thread, each thread waits its turn to display the message controlled using the semaphores, in Windows it works perfectly, however in linux threads do not wait their turn, I already researched everything that is chant and I could not reach a solution to this problem.

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

typedef struct param{
  int id;
  pthread_mutex_t lock;
  sem_t semaforo;
}valores_t;

void * olamundo(void* args){
  valores_t* p = args;
  sem_post(&p->semaforo);
  for (size_t i = 0; i < 5; i++) {
    printf("Ola mundo da thread %d\n", p->id);
  }
  sem_wait(&p->semaforo);
}

sem_t semaforo;

int main(int argc, char const *argv[]) {
  /* code */

  if(sem_init(&semaforo,0,1)){//valor inicial do semaforo começa por 1
    printf("Erro ao iniciar o semaforo\n");
  }

  valores_t p[2];
  pthread_t threads[2];

    p[0].id = 1;
    p[0].semaforo = semaforo;

    p[1].id = 2;
    p[1].semaforo = semaforo;

  for(int i = 0; i < 2; i++){//inicia as funcoes das threads
    if(pthread_create(&(threads[i]), NULL, &olamundo, &p[i]) == -1){
      printf("Erro ao inicializar a thread\n");
    }
  }

  for(int i = 0; i < 2; i++){
        if(pthread_join(threads[i], NULL)){
      printf("Erro ao sincronizar a thread\n");
    }
    }
    sem_destroy (&semaforo);
  return 0;
}
    
asked by anonymous 15.03.2018 / 20:11

0 answers