title: C how to pack mutex lock access to a structure inside a function
body: <p>I have a code that implements threads that share a series of simple counters and I grouped them in a structure to tidy up the code a litle bit. So now I have to access the counters inside the structure by its name but at the same time lock the structure wiht a mutex. So far so good no problem there, but for maintenence reasons, and code simplicity I will like to pack the mutex lock of the structure and the access to any of its members in a function , where I use as input argument the name of the member that i wish to read or change.</p>
  
  <p>I dont know if this is posible, or even convenient, I mean using a single mutex for all the counters shared by all threads may be a bad idea, givin the fact that a single counter is usually used by only two threads.</p>
  
  <p>So thats why I came here to get opinions about this and tips on how could this be acomplished</p>
  
  <hr>
  
  <p>In order to explain better what I'm looking for.</p>
  
  <p>I Have a struct of counters that is shared on different threads</p>
  
  <pre><code>struct SHARED_DATA
  {
   unsigned int counter1;
   unsigned int counter2;
   unsigned int counter3;
  }
  </code></pre>
  
  <p>Let´s say that the structure is defined global</p>
  
  <pre><code>struct SHARED_DATA shared_data = {0};
  </code></pre>
  
  <p>So, I have to access the counters individually, but I would like to pack the access to the members while simultaneusly lock the structure whit a mutex, all of this inside of a function which input argument is the name of the member of the structure that I want to read or update. Something like this</p>
  
  <pre><code>unsigned int Read_Counters(const char counter)
  {
   unsigned int value;
   pthread_mutex_lock(pthread_mutex_shared_data);
   value = shared_data.counter;
   pthread_mutex_unlock(pthread_mutex_shared_data);
   return value;
  }
  </code></pre>