Bird
Raised Fist0
FreeRTOSprogramming~5 mins

Producer-consumer pattern in FreeRTOS

Choose your learning style10 modes available
Introduction

The producer-consumer pattern helps two parts of a program work together smoothly. One part makes data (producer), and the other uses it (consumer). This keeps things organized and avoids problems when both work at the same time.

When one task creates data and another task processes it in a FreeRTOS system.
When you want to avoid losing data because the consumer is slower than the producer.
When tasks run at different speeds but need to share information safely.
When you want to use queues to pass messages or data between tasks.
When you want to keep your program responsive by separating work into tasks.
Syntax
FreeRTOS
/* Create a queue */
QueueHandle_t xQueue = xQueueCreate(queue_length, item_size);

/* Producer task */
void vProducerTask(void *pvParameters) {
    DataType data;
    for(;;) {
        // Prepare data
        xQueueSend(xQueue, &data, portMAX_DELAY);
    }
}

/* Consumer task */
void vConsumerTask(void *pvParameters) {
    DataType receivedData;
    for(;;) {
        if(xQueueReceive(xQueue, &receivedData, portMAX_DELAY) == pdPASS) {
            // Process receivedData
        }
    }
}

Use xQueueCreate() to make a queue that holds data between producer and consumer.

xQueueSend() adds data to the queue; xQueueReceive() takes data out safely.

Examples
This example creates a queue for 5 integers. The producer sends increasing numbers every 100 milliseconds.
FreeRTOS
QueueHandle_t xQueue = xQueueCreate(5, sizeof(int));

void vProducerTask(void *pvParameters) {
    int value = 0;
    for(;;) {
        xQueueSend(xQueue, &value, portMAX_DELAY);
        value++;
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}
The consumer waits for data and processes each integer it receives from the queue.
FreeRTOS
void vConsumerTask(void *pvParameters) {
    int receivedValue;
    for(;;) {
        if(xQueueReceive(xQueue, &receivedValue, portMAX_DELAY) == pdPASS) {
            // Use receivedValue here
        }
    }
}
Sample Program

This program creates a queue for 3 integers. The producer task sends numbers every 500 milliseconds. The consumer task receives and prints them. The queue safely passes data between tasks.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include <stdio.h>

QueueHandle_t xQueue;

void vProducerTask(void *pvParameters) {
    int value = 1;
    for(;;) {
        xQueueSend(xQueue, &value, portMAX_DELAY);
        printf("Produced: %d\n", value);
        value++;
        vTaskDelay(pdMS_TO_TICKS(500));
    }
}

void vConsumerTask(void *pvParameters) {
    int receivedValue;
    for(;;) {
        if(xQueueReceive(xQueue, &receivedValue, portMAX_DELAY) == pdPASS) {
            printf("Consumed: %d\n", receivedValue);
        }
    }
}

int main(void) {
    xQueue = xQueueCreate(3, sizeof(int));
    if(xQueue == NULL) {
        printf("Queue creation failed!\n");
        return 1;
    }

    xTaskCreate(vProducerTask, "Producer", 1000, NULL, 1, NULL);
    xTaskCreate(vConsumerTask, "Consumer", 1000, NULL, 1, NULL);

    vTaskStartScheduler();

    for(;;);
    return 0;
}
OutputSuccess
Important Notes

Make sure the queue size fits your data flow to avoid blocking tasks too long.

Use portMAX_DELAY to wait indefinitely for queue operations.

Always check if queue creation succeeds before using it.

Summary

The producer-consumer pattern helps tasks share data safely using queues.

Producers send data to the queue; consumers receive and process it.

FreeRTOS queues handle synchronization so tasks don't interfere with each other.

Practice

(1/5)
1.

In FreeRTOS, what is the main role of the queue in the producer-consumer pattern?

easy
A. To create new tasks dynamically
B. To handle interrupts directly
C. To manage memory allocation for tasks
D. To safely transfer data between producer and consumer tasks

Solution

  1. Step 1: Understand the producer-consumer pattern

    The pattern involves one task producing data and another consuming it, requiring safe data sharing.
  2. Step 2: Identify the role of the queue in FreeRTOS

    The queue acts as a safe buffer that holds data items, ensuring tasks do not access the same data simultaneously.
  3. Final Answer:

    To safely transfer data between producer and consumer tasks -> Option D
  4. Quick Check:

    Queue = Safe data transfer [OK]
Hint: Queues safely pass data between tasks without conflicts [OK]
Common Mistakes:
  • Thinking queues create tasks
  • Confusing queues with memory management
  • Assuming queues handle interrupts
2.

Which of the following is the correct FreeRTOS API call for a producer task to send data to a queue?

void producerTask(void *params) {
    int data = 10;
    // Send data to queue here
}
easy
A. xQueueSend(queueHandle, &data, portMAX_DELAY);
B. xQueueReceive(queueHandle, &data, portMAX_DELAY);
C. xTaskCreate(queueHandle, &data, portMAX_DELAY);
D. vTaskDelay(queueHandle);

Solution

  1. Step 1: Identify the correct API for sending data to a queue

    FreeRTOS uses xQueueSend() to send data from a producer to a queue.
  2. Step 2: Check other options for correctness

    xQueueReceive() is for receiving data, xTaskCreate() creates tasks, and vTaskDelay() delays tasks, so they are incorrect here.
  3. Final Answer:

    xQueueSend(queueHandle, &data, portMAX_DELAY); -> Option A
  4. Quick Check:

    Send data = xQueueSend [OK]
Hint: Use xQueueSend to put data into the queue [OK]
Common Mistakes:
  • Using xQueueReceive to send data
  • Confusing task creation with queue operations
  • Using delay functions instead of queue functions
3.

Consider this FreeRTOS code snippet where a producer sends integers 1 to 3 to a queue and a consumer receives them:

int data;
for (int i = 1; i <= 3; i++) {
    xQueueSend(queueHandle, &i, 0);
}
for (int j = 0; j < 3; j++) {
    xQueueReceive(queueHandle, &data, 0);
    printf("%d ", data);
}

What will be the output?

medium
A. 1 2 3
B. 3 2 1
C. 0 0 0
D. Compilation error

Solution

  1. Step 1: Analyze the producer loop

    The producer sends values 1, 2, and 3 in order to the queue without delay.
  2. Step 2: Analyze the consumer loop

    The consumer receives three values from the queue and prints them in the order received.
  3. Final Answer:

    1 2 3 -> Option A
  4. Quick Check:

    Queue preserves order = 1 2 3 [OK]
Hint: Queue keeps order; output matches sent sequence [OK]
Common Mistakes:
  • Assuming queue reverses order
  • Expecting zeros due to uninitialized data
  • Thinking code won't compile
4.

Identify the bug in this FreeRTOS consumer task code that causes it to never receive data:

void consumerTask(void *params) {
    int receivedData;
    while(1) {
        if(xQueueReceive(queueHandle, &receivedData, 0) == pdFALSE) {
            // No data received
            continue;
        }
        processData(receivedData);
    }
}
medium
A. The loop should use vTaskDelay instead of continue
B. The receive timeout is zero, causing missed data
C. The processData function is missing
D. The queue handle is not initialized

Solution

  1. Step 1: Understand xQueueReceive timeout parameter

    A zero timeout means the call returns immediately if no data is available, possibly missing data if producer is slower.
  2. Step 2: Identify why data is never received

    Because the consumer never waits, it may loop too fast and miss data arriving slightly later.
  3. Final Answer:

    The receive timeout is zero, causing missed data -> Option B
  4. Quick Check:

    Timeout 0 means no wait = missed data [OK]
Hint: Use non-zero timeout to wait for data [OK]
Common Mistakes:
  • Ignoring timeout effect on receive
  • Assuming missing queue handle causes this
  • Thinking processData absence causes no receive
5.

You want to implement a producer-consumer system where the producer sends sensor readings every 100ms, and the consumer processes them. Which FreeRTOS queue configuration and task design is best to avoid data loss and ensure timely processing?

hard
A. Use a queue with length 5 and consumer uses zero timeout on receive
B. Use a queue with length 1 and zero receive timeout in consumer
C. Use a queue with length 10 and consumer waits with portMAX_DELAY on receive
D. Use no queue and share a global variable with no synchronization

Solution

  1. Step 1: Consider queue length for buffering

    A queue length of 10 allows buffering multiple sensor readings if consumer is busy, preventing data loss.
  2. Step 2: Consider consumer receive timeout

    Using portMAX_DELAY makes consumer wait indefinitely for data, ensuring it processes every reading.
  3. Final Answer:

    Use a queue with length 10 and consumer waits with portMAX_DELAY on receive -> Option C
  4. Quick Check:

    Buffer + wait = no data loss [OK]
Hint: Use bigger queue and wait on receive to avoid loss [OK]
Common Mistakes:
  • Using too small queue causing data overwrite
  • Using zero timeout causing missed data
  • Sharing data without synchronization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard