#define THREADS_NUMBER 10
Given a function f:
void *f(void *arg){
pthread_mutex_lock(&mutex);
printf("%i\n", *((int*) arg);
pthread_mutex_unlock(&mutex);
}
I don't understand why writing this:
pthread_t threads[THREADS_NUMBER];
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_create(&threads[i], NULL, f, &i);
}
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_join(threads[i], NULL);
}
outputs this:
2 4 4 5 5 6 8 8 9 10
while writing this:
int t[10];
for(int i = 0; i < 10; i++)
t[i] = i;
pthread_t threads[THREADS_NUMBER];
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_create(&threads[i], NULL, f, &t[i]);
}
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_join(threads[i], NULL);
}
outputs this:
0 1 4 3 5 2 6 7 9 8
(In case you didn't notice the difference it's the argument passed to the thread function f
in the pthread_create
call.)