5. Deadlock
|
|
Examples of such resources are fine-grained flags, counters or queues, used to communicate between code that runs concurrently, such as an application and its interrupt handlers. The synchronization of access to those resources is an acute problem because a thread can be stopped or started at any time. |
This condition occurs when a mutex is applied but then not "unlocked". The order of applying the mutex is also important. The following code segment illustrates a potential for deadlock:. |
|
void *function1()
{
...
pthread_mutex_lock(&lock1); // Execution step 1
pthread_mutex_lock(&lock2); // Execution step 3 DEADLOCK!!!
...
}
void *function2()
{
...
pthread_mutex_lock(&lock2); // Execution step 2
pthread_mutex_lock(&lock1);
...
}
int main()
{
...
pthread_create(&thread1, NULL, function1, NULL);
pthread_create(&thread2, NULL, function2, NULL);
...
} |
|
|
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. |
|
...
pthread_mutex_lock(&mutex_1);
/* Test if already locked */
while ( pthread_mutex_trylock(&mutex_2) )
{
/* Free resource to avoid deadlock */
pthread_mutex_unlock(&mutex_1);
...
/* stall here */
...
pthread_mutex_lock(&mutex_1);
}
count++;
pthread_mutex_unlock(&mutex_1);
pthread_mutex_unlock(&mutex_2);
...
|
|
|
|