Doubt in deadlock scenario of mutex

sasikalaswathi wrote on Thursday, November 21, 2019:

Created the two mutex,

In the book, deadlock scenario stated like Deadlock occurs when two tasks cannot proceed because they are both waiting for a resource that is held by the other. I tried out the following scenario in book to trigger the deadlock condition,
1. Task A executes and successfully takes mutex X.
2. Task A is pre-empted by Task B.
3. Task B successfully takes mutex Y before attempting to also take mutex X—but mutex
X is held by Task A so is not available to Task B. Task B opts to enter the Blocked
state to wait for mutex X to be released.
4. Task A continues executing. It attempts to take mutex Y—but mutex Y is held by Task
B, so is not available to Task A. Task A opts to enter the Blocked state to wait for
mutex Y to be released.

By running the program execution, i observed the Task A and Task B get blocked always because of the timeout of portMAX_DELAY and only the idle task was running. Here generally the deadlock means what is the programming behaviour ?

Attached the code for reference.

richard_damon wrote on Thursday, November 21, 2019:

Yes, you get a deadlock because each task is waiting for the other to give back its resource so that it can proceed, but neither task can proceed so it can give back the resorce it is currently using. This is classical deadlock.

There are several ways to prevent deadlock. One is to always be consistant in the order you aquire resources, if one task aquires Y after X, then no task may aquire X after Y. This will prevent deadlock from occuring. There are some systems where the programmer assignes a number to all mutexes and related primatives, and the system will declare an error if you aquire the primatives out of order. (FreeRTOS doesn’t do this).

A second method is to detect that deadlock has possible occured but by giving the takes a finite block time, and if it expires the task backs out of the operation and releases the resources it is holding, waits a bit and tries again. This method is less used in Real Time systems as it isn’t condusive to completion by a deadline. It might be usable by non-real-time tasks within a real time system.