FreeRTOS+FAT multi-threaded use

We’ve been using FreeRTOS+FAT for several months quite successfully, but up until now only one thread has needed to access a file at a time. Now we need to implement a telemetry system which gathers system data and writes it to a file, and another thread will read the file and transmit the data. Does FreeRTOS+FAT allow both threads to be accessing a file at the same time? i.e. one thread has the file open for writing and another opens the same file for reading? Or do we need to serialise accesses to the file i.e. one thread does open/write/close and the other thread does open/read/close? We have implemented the first approach but I’ve seen a couple of system crashes under load (specifically, we seem to be failing the configASSERT in FF_UnlockFAT), so I’m wondering if we need to take the second approach.
I’m working on a Microchip SAMV71 processor with 384kB of RAM, and we have implemented FreeRTOS+FAT on a connected 8GByte SD card.

I’m surprised that you have been able to open the same file from two different threads. I would expect FF_Open to return ( FF_Error_t ) ( FF_ERR_FILE_ALREADY_OPEN | FF_OPEN ) (/* File is already open! DON’T ALLOW IT! */).

Maybe you could create a series of small files so that the producer writes to one file while the consumer reads the previous file.

Another approach, which I am using, is to create a sort of manager object that handles all requests to a particular file. I use an “active object” (a communicating finite-state machine)* implemented as a Task with a request Queue. Its event loop blocks on the request queue and handles requests for reads and writes one at a time in a “run to completion” way. In my case the “disk” is an SD card, which really can only do one thing at a time anyway.

* See:

1 Like

Thanks @carlk3 for your comments.

Just to be clear: in FreeRTOS+FAT you can either have a single handle to a file in write mode, or multiple handles a given file in read mode. It is not possible to have read and write handles to the same file.
The reason for this choice was of course: simplicity and safety.

But I think that Carl just gave some good work-arounds.

1 Like

Thanks for your comments @carlk3 and @htibosch. Hein, it’s useful to know about that constraint, thanks (I didn’t see that in the online documentation, maybe worth noting there?). Carl, thanks for the suggestions. I have been thinking along similar lines but I’m pushed for time at present so have added a high-level mutex which only allows one thread to access the files at a time, and this seems to work OK without too much performance impact. Of course this is just another method of serialising the file transactions so reads and writes are done one at a time.