title: Mutex for every element in a structure array
body: <p>I want to make every element in an array of structure thread safe by using mutex lock for accessing each element of array.</p>
  
  <p>This is my structure:</p>
  
  <pre><code>typedef struct {
    void      *value;
    void      *key;
    uint32_t  value_length;
    uint32_t  key_length;
    uint64_t  access_count;
    void      *next;
    pthread_mutex_t *mutex;
  } lruc_item;
  </code></pre>
  
  <p>I have an array of this structure, and want to use mutex locks in order to make structure elements thread safe.</p>
  
  <p>I tried using the lock on one of the array element in a function and then intensionally didn't unlock it, just to ensure that my locks are working fine, but the strange thing was that there was no deadlock and the 2nd function accessing the same array element was able to access it.</p>
  
  <p>Can some one please guide me on how to use mutexes to lock every element in a structure array (so as to make each element of the struture thread safe).  </p>
  
  <p>sample code to explain my point:</p>
  
  <pre><code>/** FUNCTION THAT CREATES ELEMENTS OF THE STRUCTURE **/
  
  lruc_item *create_item(lruc *cache) {
    lruc_item *item = NULL;
  
  item = (lruc_item *) calloc(sizeof(lruc_item), 1);
  
  item-&gt;mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
    if(pthread_mutex_init(item-&gt;mutex, NULL)) {
      perror("LRU Cache unable to initialise mutex for page");
      return NULL;
       }
  
    }
  
   return item;
  }
  
  
  set()
  {
  item = create_item(cache);
  
    pthread_mutex_lock(item-&gt;mutex);
      item-&gt;value = value;
      item-&gt;key = key;
      item-&gt;value_length = value_length;
      item-&gt;key_length = key_length;
      item-&gt;access_count = ++cache-&gt;access_count;
  
    pthread_mutex_unlock(item-&gt;mutex);     /** (LINE P) tried commenting out this to check  proper working of mutex(deadlock expected if the same "item" is accessed in another function)  **/
  
  
  }
  
  get(lruc_item *item)
  {
  
    pthread_mutex_lock(item-&gt;mutex);   /** deadlock doesn't occur when "LINE P" is commented out**/ 
      *value = item-&gt;value;
      item-&gt;access_count = ++cache-&gt;access_count;
    pthread_mutex_unlock(item-&gt;mutex);
  
  }
  </code></pre>