FreeRTOS and synchronization between one writer and two readers

730 Views Asked by At

I'm working on Modbus data logger that has two RS-485 ports handled by two tasks modbus_0_task and modbus_1_task. Both tasks use shared data_descriptors array (only for reading). These tasks will be called "readers" below.

There is also another task config_keeper_task that updates data_descriptors array (read and write). This task will be called "writer" below.

At this moment I have single mutex that protects data_descriptors array from being accessed by more than 1 task.

Everything works fine, but there is one side effect. When one "reader" takes mutex - another "reader" has to wait. This is not necessary. They only should wait when the "writer" has access.

How can I fix this?

I was thinking about counting semaphore with maximum and initial value 2.

Two readers take once, so my array could be read by both at the same time.

Writer take semaphore two times (and also waits until all readers finish). When it finishes - it gives semaphore 2 times.

Is this the normal way to do this?

1

There are 1 best solutions below

0
On BEST ANSWER

So after few experiments and some research I know that I need read/write lock pattern, and there are 2 types of simple r/w locks suitable for FreeRTOS.

First can be implemented with less resources: 1 mutex and 1 semaphore. Reader has priority when the reader and writer need access at the same time.

Second requires a bit more: 2 mutex and 2 semaphores. Writer has priority and readers must wait until writer finishes (actually all writers, because more than 1 writer can wait for access).

I found few implementations written for FreeRTOS and (to have full understanding how it works) I have rewritten this completely to fit my project.

Here is the my favourite implementation by Michael Becker:

https://github.com/michaelbecker/freertos-addons/blob/master/c/Source/read_write_lock.c