Solved

# mutex generic question

Posted on 2005-05-02
330 Views
A and B are mutexes, and are initialized
Whats the proper way to handle mutex A And B

{
while (1)
{
mutex_acquire(A);

mutex_acquire(B);

mutex_release(A);

mutex_release(B);
}
}

{
while (1)
{
mutex_acquire(B);

mutex_acquire(A);

mutex_release(B);

mutex_release(A);
}
}
0
Question by:brianpowell

LVL 45

Accepted Solution

There are several ways but the above is not one ... it may lead to deadlock when task 1 acquires A and waits for B & task2 acquires B and waits for A. Googling around for bakery algorithm and deadlock avoidance algorihtms would help. I would also recommend operating system book by silberschatz & peter galvin.
0

LVL 45

Expert Comment

One possible way would be

{
while (1)
{
mutex_acquire(A);

mutex_acquire(B);

mutex_release(B);
mutex_release(A);
}
}

{
while (1)
{
mutex_acquire(A);
mutex_acquire(B);

mutex_release(B);

mutex_release(A);
}
}

Make sure that resources/mutexes are acquired in same fixed order and released in the reverse order. It is similar to prioritizing the resources and making sure that no lower priority resource is requested if you have a larger priority resource already acquired.
0

LVL 3

Expert Comment

{
while (1)
{
mutex_acquire(A);
mutex_release(A); /* can be removed, but might interleave better */

mutex_acquire(A); /* can be removed ... */
mutex_acquire(B);
mutex_release(A); /* release task 2 if blocked */

mutex_acquire(B);
mutex_release(B);
}
}

{
while (1)
{
mutex_acquire(B);
mutex_release(B); /* release task 1 if blocked */

mutex_acquire(A); /* wait for task 1 */
mutex_acquire(B);
mutex_release(B);
mutex_release(A); /* can be removed ... */

mutex_acquire(A); /* can be removed ... */
mutex_release(A);
}
}
0

LVL 13

Expert Comment

Are you allowed to reorder the P() and V() calls ? or is this some kind of exercise you need to solve in that specific order ?
0

## Featured Post

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.