Readers/Writer Lock

Example for a Readers/Writer Lock: ~~~ struct ReadWriteLockstruct { SemaphoreHandlet xSem; SemaphoreHandlet xMutex; uint32t max_readers; } ReadWriteLock; typedef struct ReadWriteLockstruct *ReadWriteLockt; ReadWriteLock_t rwlock; void RWLockreaderstake(ReadWriteLockt rwlock) { xSemaphoreTake(rwlock->xSem, portMAXDELAY); } void RWLockreadersgive(ReadWriteLock_t rwlock) { xSemaphoreGive(rwlock->xSem); } void RWLockwritertake(ReadWriteLockt rwlock) { uintfast8_t count;
xSemaphoreTake(rwlock->xMutex, portMAX_DELAY);
for(count = 0; count < rwlock->max_readers; count++)
    xSemaphoreTake(rwlock->xSem,  portMAX_DELAY);
} void RWLockwritergive(ReadWriteLockt rwlock) { uintfast8t count; for (count=0; count < rwlock->maxreaders; count++) xSemaphoreGive(rwlock->xSem); xSemaphoreGive(rwlock->xMutex); } void main(void) { rwlock = (ReadWriteLockt)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 = (ReadWriteLockt)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

Readers/Writer Lock

Thanks for reporting back. A semaphore can be used recursively if it is created with xSemaphoreCreateRecursiveMutex().

Readers/Writer Lock

xSemaphoreCreateRecursiveMutex() doesn’t allow me to establish a maximum count or an initial count. It is also documented as for use with mutex, not semaphore. My implementation specifically wanted N-tasks to be able to read from one resource, and have one task take all the semaphores before writing. So I don’t think xSemaphoreCreateRecursiveMutex() is the right choice.