Write a C program that implements a thread-safe circular buffer using FreeRTOS and…
- User
Write a C program that implements a thread-safe circular buffer using FreeRTOS and abstracts where the buffer is persisted
Assistant
Below is an example C program that implements a thread-safe circular buffer using FreeRTOS. This implementation abstracts the persistence of the buffer, allowing you to easily switch between different storage types (e.g., RAM, external memory, file, etc.) without modifying the buffer's logic. For demonstration purposes, this example will use a simple RAM-based storage, but I'll also outline how you can abstract the storage.
Important Dependencies and Setup:
- FreeRTOS: Ensure you have FreeRTOS included in your project. If you're using an IDE, you might need to configure the include paths and library links appropriately.
- Compiler: This example assumes a standard C compiler (e.g., GCC) that supports C99 or later for
stdbool.h.
Circular Buffer Implementation with Abstracted Storage (
circular_buffer.handcircular_buffer.c):circular_buffer.h
c#ifndef CIRCULAR_BUFFER_H #define CIRCULAR_BUFFER_H #include <stdbool.h> #include "FreeRTOS.h" #include "queue.h" // For QueueHandle_t, though we won't use queues directly // Abstract Storage Interface typedef struct StorageInterface { void* (*Init)(size_t size); void (*Deinit)(void* storage); bool (*Write)(void* storage, size_t offset, const void* data, size_t length); bool (*Read)(void* storage, size_t offset, void* data, size_t length); } StorageInterface; // Circular Buffer Structure typedef struct CircularBuffer { void* storage; StorageInterface* storageInterface; size_t bufferSize; size_t writeOffset; size_t readOffset; size_t elementSize; size_t elementCount; SemaphoreHandle_t mutex; } CircularBuffer; // Circular Buffer API CircularBuffer* CB_Init(size_t bufferSize, size_t elementSize, StorageInterface* storageInterface); void CB_Deinit(CircularBuffer* cb); bool CB_Write(CircularBuffer* cb, const void* element); bool CB_Read(CircularBuffer* cb, void* element); #endif // CIRCULAR_BUFFER_H
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.