Example for a Readers/Writer Lock:
~~~
struct ReadWriteLock
struct
{
SemaphoreHandlet xSem;
SemaphoreHandle
t xMutex;
uint32t max_readers;
} ReadWriteLock;
typedef struct ReadWriteLock
struct *ReadWriteLockt;
ReadWriteLock_t rwlock;
void RWLock
readerstake(ReadWriteLock
t rwlock)
{
xSemaphoreTake(rwlock->xSem, portMAXDELAY);
}
void RWLock
readersgive(ReadWriteLock_t rwlock)
{
xSemaphoreGive(rwlock->xSem);
}
void RWLock
writertake(ReadWriteLock
t rwlock)
{
uintfast8_t count;
xSemaphoreTake(rwlock->xMutex, portMAX_DELAY);
for(count = 0; count < rwlock->max_readers; count++)
xSemaphoreTake(rwlock->xSem, portMAX_DELAY);
}
void RWLock
writergive(ReadWriteLock
t rwlock)
{
uintfast8
t count;
for (count=0; count < rwlock->maxreaders; count++)
xSemaphoreGive(rwlock->xSem);
xSemaphoreGive(rwlock->xMutex);
}
void main(void)
{
rwlock = (ReadWriteLock
t)pvPortMalloc(sizeof(struct ReadWriteLockstruct));
rwlock->xSem = xSemaphoreCreateCounting(4);
rwlock->xMutex = xSemaphoreCreateMutex();
...
vPortFree(rwlock->xMutex);
vPortFree(rwlock->xSem);
vPortFree(rwlock);
}
~~~
Previously I posted this because I thought I had trouble with a recursive xSemaphoreTake() call. I was mistaken. I had grouped the components into a struct, then only allocated the size of a pointer, not the size of the struct to rwlock:
—BAD CODE—> rwlock = (ReadWriteLock
t)pvPortMalloc(sizeof(ReadWriteLockt))
So the problem wasn’t with repeated calls to xSemaphoreTake(), but with the improper allocation or rwlock.
I hope this helps others.
Wayne