Skip to content

Commit

Permalink
Add optimisations in mutex lock
Browse files Browse the repository at this point in the history
  • Loading branch information
kar-rahul-aws committed Jan 16, 2025
1 parent a118f18 commit 1dc6661
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions light-weight-mutex.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
TickType_t xTicksToWait )
{
TaskHandle_t currentTask = xTaskGetCurrentTaskHandle();
uintptr_t expectedOwner = 0;
BaseType_t xReturn = pdFALSE;
TickType_t startTime = xTaskGetTickCount();

Expand All @@ -48,7 +47,15 @@
{
taskENTER_CRITICAL();
{
if( ( Atomic_CompareAndSwap_u32( &pxMutex->owner, ( uintptr_t ) currentTask, expectedOwner ) ) || ( Atomic_Load_u32( &pxMutex->owner ) == ( uintptr_t ) currentTask ) )
if( ( pxMutex->lock_count == 0U ) && ( Atomic_CompareAndSwap_u32( &pxMutex->owner, ( uintptr_t ) currentTask, 0 ) ) )
{
pxMutex->lock_count = 1;
xReturn = pdTRUE;
taskEXIT_CRITICAL();
goto exit;
}

if( ( uintptr_t ) Atomic_Load_u32( &pxMutex->owner ) == ( uintptr_t ) currentTask )
{
pxMutex->lock_count++;
xReturn = pdTRUE;
Expand All @@ -70,7 +77,6 @@
}
taskEXIT_CRITICAL();
taskYIELD();
expectedOwner = 0;
}

exit:
Expand Down Expand Up @@ -101,7 +107,7 @@

taskENTER_CRITICAL();
{
if( Atomic_Load_u32( &pxMutex->owner ) != ( uintptr_t ) currentTask )
if( ( uintptr_t ) Atomic_Load_u32( &pxMutex->owner ) != ( uintptr_t ) currentTask )
{
taskEXIT_CRITICAL();
return pdFALSE;
Expand All @@ -111,9 +117,7 @@

if( pxMutex->lock_count == 0U )
{
uintptr_t expectedOwner = ( uintptr_t ) currentTask;

if( !Atomic_CompareAndSwap_u32( &pxMutex->owner, 0, expectedOwner ) )
if( !Atomic_CompareAndSwap_u32( &pxMutex->owner, 0, ( uintptr_t ) currentTask ) )
{
/* This should never happen if used correctly */
configASSERT( pdFALSE );
Expand Down

0 comments on commit 1dc6661

Please sign in to comment.