Skip to content

Commit

Permalink
lib: system: freertos: mutex: change to use atomic_int instead of fre…
Browse files Browse the repository at this point in the history
…ertos construct

As freertos does not seem to provide way to statically initialize semaphore,
use atomic int which provides this functionality.

Signed-off-by: Ben Levinsky <ben.levinsky@xilinx.com>
  • Loading branch information
Ben Levinsky authored and wjliang committed Aug 3, 2018
1 parent 4e670c5 commit 10a0d5b
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions lib/system/freertos/mutex.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,22 @@
#ifndef __METAL_FREERTOS_MUTEX__H__
#define __METAL_FREERTOS_MUTEX__H__

#include <metal/assert.h>
#include "FreeRTOS.h"
#include "semphr.h"

#include <metal/atomic.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
SemaphoreHandle_t m;
atomic_int v;
} metal_mutex_t;

/*
* METAL_MUTEX_INIT - used for initializing an mutex elmenet in a static struct
* or global
*/
#define METAL_MUTEX_INIT(m) { NULL }
#define METAL_MUTEX_INIT(m) { ATOMIC_VAR_INIT(0) }
/*
* METAL_MUTEX_DEFINE - used for defining and initializing a global or
* static singleton mutex
Expand All @@ -42,40 +40,34 @@ typedef struct {

static inline void __metal_mutex_init(metal_mutex_t *mutex)
{
metal_assert(mutex);
mutex->m = xSemaphoreCreateMutex();
metal_assert(mutex->m != NULL);
atomic_store(&mutex->v, 0);
}

static inline void __metal_mutex_deinit(metal_mutex_t *mutex)
{
metal_assert(mutex && mutex->m != NULL);
vSemaphoreDelete(mutex->m);
mutex->m=NULL;
(void)mutex;
}

static inline int __metal_mutex_try_acquire(metal_mutex_t *mutex)
{
metal_assert(mutex && mutex->m != NULL);
return xSemaphoreTake(mutex->m, ( TickType_t ) 0 );
return 1 - atomic_flag_test_and_set(&mutex->v);
}

static inline void __metal_mutex_acquire(metal_mutex_t *mutex)
{
metal_assert(mutex && mutex->m != NULL);
xSemaphoreTake(mutex->m, portMAX_DELAY);
while (atomic_flag_test_and_set(&mutex->v)) {
;
}
}

static inline void __metal_mutex_release(metal_mutex_t *mutex)
{
metal_assert(mutex && mutex->m != NULL);
xSemaphoreGive(mutex->m);
atomic_flag_clear(&mutex->v);
}

static inline int __metal_mutex_is_acquired(metal_mutex_t *mutex)
{
metal_assert(mutex && mutex->m != NULL);
return (NULL == xSemaphoreGetMutexHolder(mutex->m)) ? 0 : 1;
return atomic_load(&mutex->v);
}

#ifdef __cplusplus
Expand Down

0 comments on commit 10a0d5b

Please sign in to comment.