So I'm learning how to use threads on C, and I wrote down this code.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define number 3
void *funct(void *tid){
printf("Thread %d\n", *((int*)tid));
sleep(10);
printf("Thread %d finishes\n", *((int*)tid));
pthread_exit(NULL);
}
int main() {
pthread_t threads[number];
int i, status;
printf("Pid: %d\n", getpid());
for (i = 0; i < number; i++) {
printf("Thread number %d\n", i);
status = pthread_create(&threads[i], NULL, funct, (void*)&i);
if(status != 0){
printf("Error en la creación del hilo. La función devuelve %d\n", status);
exit(-1);
}
}
for (i = 0; i < number; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
My problem is that I want to identify them on funct
with their number, but sometimes the output is wrong.
Pid: 10142
Thread number 0
Thread number 1
Thread number 2
Thread 2
Thread 1
Thread 0
Thread 0 finishes
Thread 0 finishes
Thread 0 finishes
It shouldn't be printing Thread 0 finishes
3 times. I suppose the content of tid
changes between the calls to the threads and that's why it print another values. How can I fix this?