Bird
Raised Fist0
FreeRTOSprogramming~5 mins

Counting semaphore for resource pools in FreeRTOS

Choose your learning style10 modes available
Introduction

A counting semaphore helps manage a limited number of resources shared by many tasks. It keeps track of how many resources are free or used.

When multiple tasks need to share a fixed number of identical resources, like printers or buffers.
To control access to a pool of connections or hardware devices.
When you want to limit how many tasks can enter a critical section at the same time.
To avoid conflicts and ensure safe use of shared resources.
When you want tasks to wait if no resources are available and continue when one is free.
Syntax
FreeRTOS
SemaphoreHandle_t xSemaphore = xSemaphoreCreateCounting( maxCount, initialCount );

// To take (acquire) a resource:
if( xSemaphoreTake( xSemaphore, portMAX_DELAY ) == pdTRUE ) {
    // Use resource
}

// To give (release) a resource:
xSemaphoreGive( xSemaphore );

maxCount is the total number of resources available.

initialCount is how many resources are free at the start.

Examples
Creates a counting semaphore for 3 resources, all free initially.
FreeRTOS
SemaphoreHandle_t xSemaphore = xSemaphoreCreateCounting( 3, 3 );
Task waits until a resource is free, uses it, then releases it.
FreeRTOS
if( xSemaphoreTake( xSemaphore, portMAX_DELAY ) == pdTRUE ) {
    // Use resource
    xSemaphoreGive( xSemaphore );
}
Sample Program

This program creates a counting semaphore with 2 resources. Three tasks try to get a resource. Only two can have it at once; the third waits until one releases.

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

SemaphoreHandle_t xCountingSemaphore;

void vTaskFunction( void *pvParameters ) {
    const char *taskName = (const char *) pvParameters;
    if( xSemaphoreTake( xCountingSemaphore, portMAX_DELAY ) == pdTRUE ) {
        printf("%s acquired a resource\n", taskName);
        vTaskDelay( 1000 / portTICK_PERIOD_MS ); // Simulate using resource
        printf("%s releasing a resource\n", taskName);
        xSemaphoreGive( xCountingSemaphore );
    }
    vTaskDelete(NULL);
}

int main( void ) {
    xCountingSemaphore = xSemaphoreCreateCounting( 2, 2 ); // 2 resources
    if( xCountingSemaphore == NULL ) {
        // Semaphore was not created successfully
        return 1;
    }

    xTaskCreate( vTaskFunction, "Task1", 1000, "Task1", 1, NULL );
    xTaskCreate( vTaskFunction, "Task2", 1000, "Task2", 1, NULL );
    xTaskCreate( vTaskFunction, "Task3", 1000, "Task3", 1, NULL );

    vTaskStartScheduler();

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

Always check if the semaphore was created successfully before using it.

Use portMAX_DELAY to wait indefinitely for a resource, or a timeout value to avoid waiting forever.

Remember to give back the semaphore after using the resource to avoid deadlocks.

Summary

Counting semaphores track how many identical resources are free or used.

Use xSemaphoreCreateCounting to create one with max and initial counts.

Tasks take and give the semaphore to safely share resources.

Practice

(1/5)
1. What is the main purpose of a counting semaphore in FreeRTOS when managing resource pools?
easy
A. To track the number of available identical resources
B. To create tasks with different priorities
C. To store data between tasks
D. To handle interrupts directly

Solution

  1. Step 1: Understand counting semaphore role

    A counting semaphore keeps track of how many identical resources are free or in use.
  2. Step 2: Compare with other options

    Creating tasks, storing data, or handling interrupts are not roles of counting semaphores.
  3. Final Answer:

    To track the number of available identical resources -> Option A
  4. Quick Check:

    Counting semaphore = resource count tracker [OK]
Hint: Counting semaphore counts free resources, not tasks or data [OK]
Common Mistakes:
  • Confusing counting semaphore with binary semaphore
  • Thinking it creates or manages tasks
  • Assuming it stores data
2. Which of the following is the correct way to create a counting semaphore with a maximum count of 5 and an initial count of 3 in FreeRTOS?
easy
A. xSemaphoreCreateCounting(3, 5);
B. xSemaphoreCreateCounting(5, 3);
C. xSemaphoreCreateCounting(5);
D. xSemaphoreCreateCounting(3);

Solution

  1. Step 1: Recall function parameters

    The function xSemaphoreCreateCounting takes max count first, then initial count.
  2. Step 2: Match parameters to options

    xSemaphoreCreateCounting(5, 3); uses (5, 3) which means max count 5 and initial count 3, correct order.
  3. Final Answer:

    xSemaphoreCreateCounting(5, 3); -> Option B
  4. Quick Check:

    Max count first, initial count second [OK]
Hint: Remember max count is first parameter, initial count second [OK]
Common Mistakes:
  • Swapping max and initial count parameters
  • Using only one parameter
  • Confusing with binary semaphore creation
3. Given the following code snippet, what will be the value of the semaphore count after both tasks successfully take the semaphore once?
SemaphoreHandle_t sem = xSemaphoreCreateCounting(3, 3);
xSemaphoreTake(sem, 0);
xSemaphoreTake(sem, 0);
medium
A. 3
B. 0
C. 2
D. 1

Solution

  1. Step 1: Understand initial semaphore count

    The semaphore starts with count 3 (max and initial both 3).
  2. Step 2: Subtract count for each take

    Each xSemaphoreTake reduces count by 1 if successful. Two takes reduce count by 2.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    3 - 2 takes = 1 [OK]
Hint: Each take reduces count by one if successful [OK]
Common Mistakes:
  • Assuming count stays the same after take
  • Confusing take with give operation
  • Thinking count can go below zero
4. Identify the error in this code snippet that uses a counting semaphore for a resource pool:
SemaphoreHandle_t sem = xSemaphoreCreateCounting(2, 2);
xSemaphoreGive(sem);
medium
A. xSemaphoreGive should be called before creation
B. xSemaphoreCreateCounting parameters are reversed
C. Calling xSemaphoreGive when semaphore count is at max causes overflow
D. No error, code is correct

Solution

  1. Step 1: Check initial semaphore count

    The semaphore is created with max count 2 and initial count 2, so it's full.
  2. Step 2: Analyze xSemaphoreGive call

    Giving semaphore when count is already max causes overflow error or undefined behavior.
  3. Final Answer:

    Calling xSemaphoreGive when semaphore count is at max causes overflow -> Option C
  4. Quick Check:

    Giving at max count causes overflow [OK]
Hint: Don't give semaphore if count is already at max [OK]
Common Mistakes:
  • Ignoring semaphore max count limits
  • Swapping max and initial counts
  • Calling give before creating semaphore
5. You have a resource pool of 4 identical devices. You want to create a counting semaphore to manage access. Initially, 2 devices are free. Which code snippet correctly creates and initializes the semaphore for this scenario?
hard
A. SemaphoreHandle_t sem = xSemaphoreCreateCounting(4, 2);
B. SemaphoreHandle_t sem = xSemaphoreCreateCounting(2, 2);
C. SemaphoreHandle_t sem = xSemaphoreCreateCounting(4, 4);
D. SemaphoreHandle_t sem = xSemaphoreCreateCounting(2, 4);

Solution

  1. Step 1: Identify max and initial counts

    Max count is total devices (4), initial count is free devices (2).
  2. Step 2: Match parameters to function call

    Correct call is xSemaphoreCreateCounting(4, 2) with max 4 and initial 2.
  3. Final Answer:

    SemaphoreHandle_t sem = xSemaphoreCreateCounting(4, 2); -> Option A
  4. Quick Check:

    Max = total devices, initial = free devices [OK]
Hint: Max count = total resources, initial count = free resources [OK]
Common Mistakes:
  • Swapping max and initial counts
  • Setting initial count higher than max
  • Using max count less than total resources
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