Mbed_critical utils as RAII-style class

Hi there –

(cc @vcoubard @donatien)

I’m currently working on a circular buffer based on Mbed’s CircularBuffer class with the addition of a few methods such as peek at position and has pattern.

I find myself copy pasting a lot of core_util_critical_section_enter() and core_util_critical_section_exit().

I like to put my early return conditions at the top of my functions but with those core_util functions, it looks ugly.

I wish there was a way to “acquire” the critical section with RAII and release it naturally when it goes out of scope, just like std::lock_guard would do.

I’m wondering if mbed_critical would be crapped in a class implementing BasicLockable to provide the needed behavior? What would be the downside?

Or is it a stupid idea? and is so please let me know!

Thanks for your help!

Best,
– Ladislas

Could you use
https://os.mbed.com/docs/mbed-os/v6.10/apis/criticalsectionlock.html
?

Ah thank you! This is almost exactly what I need :slight_smile:

The example uses:

void increment(void)
{
    for (int i = 0; i < value; i++) {
#if (USE_CRITICAL_SECTION_LOCK == 1)
        CriticalSectionLock  lock;        // <----HERE
#endif
        counter += 1;
    }
}

It works but I find it strange that you need to instantiate an object to lock a critical section. Unless you look at the implementation, there is no way to know what is does:

CriticalSectionLock::CriticalSectionLock()
{
    core_util_critical_section_enter();
}

CriticalSectionLock::~CriticalSectionLock()
{
    core_util_critical_section_exit();
}

I still would prefer the “standard” way:

class CircularBuffer {
  public:
    auto pop(T& data) -> bool
    {
        const std::lock_guard<mbed::CriticalSectionLock> lock(_lock); 
        // ...
    }

  private:
    CriticalSectionLock _lock {};
}

If that makes sense.

It’s just a simple PR to add lock() and unlock() to CriticalSection

Hi Ladislas,

you could always propose a PR to do the update and then the core team can review / approve ? :slight_smile:

Anna

It’s just a simple PR to add lock() and unlock() to CriticalSection

You need a new class otherwise when instantiated, CriticalSectionLock will enter the critical section.

You’re right, it’s a breaking change if I remove the critical section enter/exit from the ctor/dtor.

I’ll raise a PR, let people review. Adding a new class will break the DRY principle and make it harder for people to see the difference between the two.

I’ll tend to side with the “more compatible with STL” approach, so in case the PR is blocked, I can easily make my own :slight_smile: