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
Here is an example C program that implements a thread-safe circular buffer using FreeRTOS and abstracts where the buffer is persisted:
c#include <stdlib.h> #include <string.h> #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "circular_buffer.h" // Define the maximum size of the circular buffer #define BUFFER_SIZE 256 // Define the circular buffer structure typedef struct { void* buffer; // Pointer to the buffer size_t item_size; // Size of each item in the buffer size_t head; // Index of the head of the buffer size_t tail; // Index of the tail of the buffer size_t count; // Number of items in the buffer SemaphoreHandle_t lock;// Semaphore for locking the buffer } circular_buffer_t; // Create a new circular buffer circular_buffer_t* circular_buffer_create(size_t item_size) { circular_buffer_t* buffer = (circular_buffer_t*) malloc(sizeof(circular_buffer_t)); if (buffer == NULL) { return NULL; } buffer->buffer = malloc(BUFFER_SIZE * item_size); if (buffer->buffer == NULL) { free(buffer); return NULL; } buffer->item_size = item_size; buffer->head = 0; buffer->tail = 0; buffer->count = 0; buffer->lock = xSemaphoreCreateMutex(); return buffer; } // Destroy a circular buffer void circular_buffer_destroy(circular_buffer_t* buffer) { free(buffer->buffer); vSemaphoreDelete(buffer->lock); free(buffer); } // Add an item to the circular buffer int circular_buffer_add(circular_buffer_t* buffer, const void* item) { if (buffer == NULL || item == NULL) { return -1; } xSemaphoreTake(buffer->lock, portMAX_DELAY); if (buffer->count == BUFFER_SIZE) { xSemaphoreGive(buffer->lock); return -1; } void* buffer_ptr = (char*) buffer->buffer + (buffer->head * buffer->item_size); memcpy(buffer_ptr, item, buffer->item_size); buffer->head = (buffer->head + 1) % BUFFER_SIZE; buffer->count++; xSemaphoreGive(buffer->lock); return 0; } // Remove an item from the circular buffer int circular_buffer_remove(circular_buffer_t* buffer, void* item) { if (buffer == NULL || item == NULL) { return -1; } xSemaphoreTake(buffer->lock, portMAX_DELAY); if (buffer->count == 0) { xSemaphoreGive(buffer->lock); return -1; } void* buffer_ptr = (char*) buffer->buffer + (buffer->tail * buffer->item_size); memcpy(item, buffer_ptr, buffer->item_size); buffer->tail = (buffer->tail + 1) % BUFFER_SIZE; buffer->count--; xSemaphoreGive(buffer->lock); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.