Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 381

mutex generic question

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
brianpowell
• 2
1 Solution

Commented:
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

Commented:
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

Commented:

{
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 ... */