Estoy practicando multi-hilo.
Creo dos subprocesos posix que muestran un texto en la pantalla (bucle infinito), pero parece que solo se ejecuta el primer subproceso. Modifico el programa sin bucles, el primer hilo se imprime, el siguiente es el segundo hilo. Parece que mi hilo no es paralelo, el primer hilo tiene que terminar antes de que comience el segundo hilo. ¿Cómo puedo hacerlos paralelos?
Gracias,
hdr.h
#ifndef HDR_HDR_H_ #define HDR_HDR_H_ #define HDR_HDR_H_ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #endif /* HDR_HDR_H_ */multihilo01.c
#include "../hdr/myfunc.h" pthread_mutex_t lock; int main(int argc, char **argv) { pthread_t tid01; pthread_t tid02; void * status01; void * status02; pthread_create(&tid01, NULL, PrintOut01(), NULL); pthread_create(&tid02, NULL, PrintOut02(), NULL); pthread_join(&tid01, &status01); pthread_join(&tid02, &status02); return 0;}
mifunc.h
#ifndef HDR_MYFUNC_H_ #define HDR_MYFUNC_H_ #include "../hdr/hdr.h" void * PrintOut01 (void); void * PrintOut02 (void); #endif /* HDR_MYFUNC_H_ */mifunc.c
#include "../hdr/hdr.h" extern pthread_mutex_t lock; void * PrintOut01 () { while (1) { pthread_mutex_lock(&lock); printf ("This is thread 01\n"); pthread_mutex_unlock(&lock); } } void * PrintOut02 () { while (1) { pthread_mutex_lock(&lock); printf ("This is thread 02\n"); pthread_mutex_unlock(&lock); } }Es porque está llamando a las funciones en su llamada pthread_create , no está pasando los punteros de función.
Compara lo incorrecto
pthread_create(&tid01, NULL, PrintOut01(), NULL);con el correcto
pthread_create(&tid01, NULL, PrintOut01, NULL); Si elimina los bucles en las funciones y crea los subprocesos como lo hace en el código de la pregunta, entonces pthread_create usará lo que devuelva de las funciones como puntero a la función de subproceso, y a menos que devuelva un puntero a un función tendrá un comportamiento indefinido .