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
#include "FreeRTOS.h" #include "task.h" #include "port.h" #include "stdio.h" #include "string.h" #include "pthread.h"
#define BUFFER_SIZE 10
typedef struct { char data[BUFFER_SIZE]; int head; int tail; int count; } CircularBuffer;
CircularBuffer buffer;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* producer(void* arg) { char* data = (char*) arg; int size = strlen((const char*) data);
codeif (size > BUFFER_SIZE) { printf("Data size exceeds buffer size.\n"); return NULL; } pthread_mutex_lock(&mutex); buffer.count = (buffer.count + size) % BUFFER_SIZE; buffer.head = (buffer.head + size) % BUFFER_SIZE; strncpy(buffer.data + buffer.head, data, size); buffer.head = (buffer.head + 1) % BUFFER_SIZE; pthread_mutex_unlock(&mutex); return NULL;}
void* consumer(void* arg) { pthread_mutex_lock(&mutex);
codeif (buffer.count == 0) { printf("Buffer is empty.\n"); pthread_mutex_unlock(&mutex); return NULL; } int index = (buffer.tail + BUFFER_SIZE - 1) % BUFFER_SIZE; char* data = &buffer.data[index]; pthread_mutex_unlock(&mutex); return data;}
CircularBuffer* create_buffer() { CircularBuffer* buf = malloc(sizeof(CircularBuffer)); if (!buf) { printf("Failed to allocate memory for circular buffer.\n"); return NULL; }
codebuf->head = 0; buf->tail = 0; buf->count = 0; return buf;}
void destroy_buffer(CircularBuffer* buf) { free(buf); }
int main() { CircularBuffer* buf = create_buffer();
code// Create producer and consumer threads pthread_t producer_thread, consumer_thread; char* data = "Hello, World!"; pthread_create(&producer_thread, NULL, producer, (void*) data); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); destroy_buffer(buf); 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.