CriticalSectionLock
The CriticalSectionLock class provides a mechanism to access a resource without interruption. With the CriticalSectionLock::enable
API, you can enter critical section with interrupts disabled. The CriticalSectionLock::disable()
API is the exit from critical section, and the last exit call restores the state of interrupts.
CriticalSectionLock class is based on RAII approach. In other words, the constructor acquires the lock, and the destructor destroys it automatically when it is out of scope. We do not recommend you use CriticalSectionLock as global or a member of a class because you will enter critical section on object creation, and all interrupts will be disabled.
Mbed OS supports nesting of critical section, and the destructor enables interrupts only when you exit from the last nested critical section.
Note: You must not use time-consuming operations, standard library and RTOS functions inside critical section.
CriticalSectionLock class reference
Static Public Member Functions | |
static void | enable () |
Mark the start of a critical section. More... | |
static void | disable () |
Mark the end of a critical section. More... |
CriticalSectionLock example
Here is an example that demonstrates a race condition issue and how CriticalSectionLock helps resolves it.
/*
* Copyright (c) 2017 - 2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#define USE_CRITICAL_SECTION_LOCK 1 // Set 0 to see race condition
// Note: Might require few runs to see race condition
#define THREAD_CNT 8
int32_t value = 100000;
volatile int32_t counter = 0;
void increment(void)
{
for (int i = 0; i < value; i++) {
#if (USE_CRITICAL_SECTION_LOCK == 1)
CriticalSectionLock lock;
#endif
counter += 1;
}
}
int get_count(void)
{
if (counter == (value * THREAD_CNT)) {
printf("No Race condition\n");
} else {
printf("Race condition\n");
}
return counter;
}
int main()
{
Thread counter_thread[THREAD_CNT];
for (int i = 0; i < THREAD_CNT; i++) {
counter_thread[i].start(callback(increment));
}
// Wait for the threads to finish
for (int i = 0; i < THREAD_CNT; i++) {
counter_thread[i].join();
}
printf("Counter = %d\n", get_count());
}