The problem is in following:
I want to write a short program that creates 10 threads and each prints a tread “id” that is passed to thread function by pointer.
Full code of the program is below:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
struct params {
pthread_mutex_t mutex;
int id;
};
typedef struct params params_t;
void* hello(void* arg){
int id;
pthread_mutex_lock(&(*(params_t*)(arg)).mutex);
id = (*(params_t*)(arg)).id;
pthread_mutex_unlock(&(*(params_t*)(arg)).mutex);
printf("Hello from %d\n", id);
}
int main() {
pthread_t threads[10];
params_t params;
pthread_mutex_init (¶ms.mutex , NULL);
int i;
for(i = 0; i < 10; i++) {
params.id = i;
if(pthread_create(&threads[i], NULL, hello, ¶ms));
}
for(i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
The supposed output is (not necessary in this order):
Hello from 0
....
Hello from 9
Actual result is:
Hello from 2
Hello from 3
Hello from 3
Hello from 4
Hello from 5
Hello from 6
Hello from 8
Hello from 9
Hello from 9
Hello from 9
I tried to place mutex in different places in hello() function, but it didn’t help.
How should I implement thread sync?
EDIT: Supposed result is not necessary 0…9 it can be any combination of these numbers, but each one should appear only one time.
There are two problems:
A. You’re using a
lockbutmainis unaware of this lock.B. A
lockis not enough in this case. What you would want is for threads to cooperate by signalling each other (because you wantmainto not increment the variable until a thread says that it is done printing it). You can use apthread_cond_tto achieve this (Look here to learn more about this). This boils down to the following code (basically, I added an appropriate usage ofpthread_cond_tto your code, and a bunch of comments explaining what is going on):I see that the example you are trying is a toy program to probably learn about the POSIX thread library. In the real world, as we all know this can be done much faster without even using threads. But you already know this.