Consider two producer tasks sending integers to a single consumer task via a FreeRTOS queue. What will the consumer print?
QueueHandle_t queue;
void producer1(void *params) {
int val = 1;
while(1) {
xQueueSend(queue, &val, portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void producer2(void *params) {
int val = 2;
while(1) {
xQueueSend(queue, &val, portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(150));
}
}
void consumer(void *params) {
int received;
for (int i = 0; i < 5; i++) {
xQueueReceive(queue, &received, portMAX_DELAY);
printf("Received: %d\n", received);
}
vTaskDelete(NULL);
}
int main() {
queue = xQueueCreate(10, sizeof(int));
xTaskCreate(producer1, "Producer1", 1000, NULL, 1, NULL);
xTaskCreate(producer2, "Producer2", 1000, NULL, 1, NULL);
xTaskCreate(consumer, "Consumer", 1000, NULL, 2, NULL);
vTaskStartScheduler();
return 0;
}Consider the delay times and task priorities to understand the order of messages received.
The consumer receives messages in the order they are sent to the queue. Producer1 sends every 100ms, Producer2 every 150ms. The consumer prints the first 5 received values, which alternate mostly as 1 then 2 due to timing.
In FreeRTOS, when multiple producer tasks send data to a single consumer task, which synchronization method ensures safe data transfer without data loss?
Think about a structure that can hold multiple data items and manage access automatically.
A FreeRTOS queue is designed to safely hold multiple data items from multiple producers and deliver them to a single consumer, handling synchronization internally.
Examine the code snippet below. Multiple producers write to a shared buffer without synchronization. What is the main cause of data corruption?
char sharedBuffer[10]; void producer(void *params) { const char *msg = (const char *)params; while(1) { strcpy(sharedBuffer, msg); // No synchronization vTaskDelay(pdMS_TO_TICKS(50)); } } void consumer(void *params) { while(1) { printf("Buffer: %s\n", sharedBuffer); vTaskDelay(pdMS_TO_TICKS(100)); } }
Think about what happens when multiple tasks write to the same memory without coordination.
Without mutual exclusion (like a mutex), multiple producers can write to sharedBuffer simultaneously, causing race conditions and data corruption.
Choose the correct code snippet to create a queue that holds 5 integers for multiple producers and a single consumer.
Check the order and meaning of parameters in xQueueCreate.
xQueueCreate takes two parameters: the number of items the queue can hold, and the size of each item in bytes. Option A uses correct order and types.
In a FreeRTOS system with multiple producers and a single consumer, producers sometimes send data faster than the consumer can handle. Which approach best prevents data loss?
Think about how to buffer data and control producer flow to avoid losing messages.
Increasing queue length buffers more data. Blocking producers when the queue is full prevents data loss by waiting until the consumer processes items.
