I am working for the first time on a "large" scale with threads in C and i am uncertain about how to properly use multiple mutex with each mutex protecting a structure and the structure possibly being manipulated by multiple threads
consider the following code
#include <pthread.h>
#include <stdlib.h>
struct example{
int parameter;
};
void *do_something(void *argument);
int main(){
struct example *ex1 = (struct example *) malloc(sizeof(struct example));
struct example *ex2 = (struct example *) malloc(sizeof(struct example));
ex1->parameter = 5;
ex2->parameter = 4;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_create(&thread1,NULL, do_something, ex1);
pthread_create(&thread2,NULL, do_something, ex1);
pthread_create(&thread3,NULL, do_something, ex2);
pthread_create(&thread4,NULL, do_something, ex2);
return 0;
}
void *do_something(void *argument){
struct example *something = (struct example *) argument;
something->parameter = something->parameter 1;
return NULL;
}
what is the best way to assign two mutex one for ex1 and the other for ex2 in the code above? i have a couple of ideas in my mind but i'm not sure which one will work and which will make a catastrophe for example
struct parameters{
struct example *example;
pthread_mutex_t lock;
};
struct parameters *param
pthread_create(&thread1,NULL, do_something, param);
or maybe even including the mutex in the very first structure so it's like
struct example{
int parameter;
pthread_mutex_t lock;
};
i'm not sure which is better or whether both are usuable at all, i'd love to hear some opinions, pointers or even readup recommendations before i commit into a method and it turns out to be a catastrophe
CodePudding user response:
what is the best way to assign two mutex one for ex1 and the other for ex2 in the code above?
The most natural way to associate a separate mutex with each instance of a given structure type is to make it a member of that type. That's not always possible, but when you form the association any other way, you are susceptible to the problem of how to determine from a given structure instance which is the mutex that goes with it.
That is, if it is struct example
for which you want mutexes then
struct example{ int parameter; pthread_mutex_t lock; };