Bird
Raised Fist0
FreeRTOSprogramming~10 mins

Producer-consumer pattern in FreeRTOS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Producer-consumer pattern
Producer Task
↓
Produce Data
↓
Send to Queue
↓
Consumer Task
↓
Receive from Queue
↓
Consume Data
↓
Repeat
The producer creates data and sends it to a queue. The consumer waits for data from the queue and processes it.
Execution Sample
FreeRTOS
void producer(void *pvParameters) {
  int count = 0;
  while(1) {
    xQueueSend(queue, &count, portMAX_DELAY);
    count++;
  }
}

void consumer(void *pvParameters) {
  int received;
  while(1) {
    xQueueReceive(queue, &received, portMAX_DELAY);
    // process received
  }
}
Producer sends incrementing numbers to a queue; consumer receives and processes them.
Execution Table
StepTaskActionQueue StateData Sent/ReceivedOutput
1ProducerProduce 0[]0
2ProducerSend 0 to queue[0]0
3ConsumerReceive from queue[]0Process 0
4ProducerProduce 1[]1
5ProducerSend 1 to queue[1]1
6ConsumerReceive from queue[]1Process 1
7ProducerProduce 2[]2
8ProducerSend 2 to queue[2]2
9ConsumerReceive from queue[]2Process 2
10ProducerProduce 3[]3
11ProducerSend 3 to queue[3]3
12ConsumerReceive from queue[]3Process 3
13ExitStop after 4 cycles[]End of trace
💡 Stopped after 4 produce-consume cycles for demonstration
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
count (Producer)012344
received (Consumer)N/A01233
queueempty[0]empty[1]emptyempty
Key Moments - 3 Insights
Why does the consumer wait when the queue is empty?
Because xQueueReceive uses portMAX_DELAY, the consumer blocks until data arrives, as shown in execution_table rows 3, 6, 9, and 12.
What happens if the producer tries to send when the queue is full?
In this example, the queue size is large enough, but normally xQueueSend would block or fail; here, the producer always succeeds because the consumer removes items promptly (see queue state in execution_table).
Why does the queue alternate between empty and having one item?
Because the producer sends one item, then the consumer receives it before the next send, so the queue never holds more than one item at a time (see queue state column).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5. What is the queue state after the producer sends data?
A[1]
B[]
C[0,1]
D[0]
💡 Hint
Check the 'Queue State' column at step 5 in the execution_table.
At which step does the consumer first receive data?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Task' and 'Action' columns to find when consumer receives data.
If the producer increments count by 2 instead of 1, how would the 'Data Sent/Received' column change at step 8?
AIt would show 3
BIt would show 2
CIt would show 4
DIt would show 1
💡 Hint
Check how count increments affect data sent at each produce step in variable_tracker.
Concept Snapshot
Producer-consumer pattern in FreeRTOS:
- Producer task creates data and sends it to a queue.
- Consumer task waits and receives data from the queue.
- Use xQueueSend and xQueueReceive for communication.
- Consumer blocks if queue empty; producer blocks if queue full.
- Ensures safe data exchange between tasks.
Full Transcript
This visual execution shows the producer-consumer pattern in FreeRTOS. The producer task creates data (an incrementing count) and sends it to a queue using xQueueSend. The consumer task waits for data using xQueueReceive and processes it. The queue acts as a safe buffer between tasks. The execution table traces each step: producing data, sending to queue, receiving from queue, and processing. Variables like count and received change as data flows. Key moments clarify why the consumer waits when the queue is empty and how the queue state changes. The visual quiz tests understanding of queue states and data flow. This pattern helps tasks communicate safely and efficiently in embedded systems.

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