I'm studying mutexes and deadlocks in c++ pthreads from http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
I understood them but i stacked at a point. I didn't understand what is the problem of the below code. Can you explain it with simple and clear words please? I quoted from this site:
Mutex Deadlock: ... Be careful when applying two or more mutexes to a section of code. If the first pthread_mutex_lock is applied and the second pthread_mutex_lock fails due to another thread applying a mutex, the first mutex may eventually lock all other threads from accessing data including the thread which holds the second mutex. The threads may wait indefinitely for the resource to become free causing a deadlock. It is best to test and if failure occurs, free the resources and stall before retrying.
01 ...
02 pthread_mutex_lock(&mutex_1);
03 while ( pthread_mutex_trylock(&mutex_2) ) /* Test if already locked */
04 {
05 pthread_mutex_unlock(&mutex_1); /* Free resource to avoid deadlock */
06 ...
07 /* stall here */
08 ...
09 pthread_mutex_lock(&mutex_1);
10 }
11 count++;
12 pthread_mutex_unlock(&mutex_1);
13 pthread_mutex_unlock(&mutex_2);
14 ...
Thanks in advance.