previous | start | next

Deadlock with mutex

Suppose two (or more) threads use 2 objects that can only be used by one thread at a time (serially reusable). Each thread might use just one of the objects initially and then try to get the second one as well:

void thr1()                         void thr2()              
{                                   {                        
  pthread_mutex_lock(&m1);                pthread_mutex_lock(&m2);   
  /* use object 1 */                  /* use object 2 */             
  ...                                 ...                            
  pthead_mutex_lock(&m2);                 pthead_mutex_lock(&m1);    
  /* use objects 1 and 2 */           /* use objects 1 and 2 */  
  ...                                 ...                            
  pthread_mutex_unlock(&m2);              pthread_mutex_unlock(&m1); 
  pthread_mutex_unlock(&m1);              pthread_mutex_unlock(&m2); 
}                                   }                            

Can result in deadlock! How?



previous | start | next