1
I’m using the Linux pthreads library to try out the functionality of threads, 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, on Windows works perfectly, but in linux threads do not wait their turn, I already researched everything that is singing and could not find 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;
}
https://stackoverflow.com/questions/30434745/c-11-threads-different-behaviour-on-linux-and-windows
– Leila
i was able to fix this problem in the other post I did on stackoverflow https://stackoverflow.com/questions/49503594/using-parameters-with-threads
– Davi Wesley
the error is obvious (and was pointed out in the other OS): you are reversing the order fas operations sem_wait and sem_post...
– zentrunix