Sema4.h
#ifndef SEMA4_H__
#define SEMA4_H__
#include "freertos/semphr.h"
/*
* Handy class to provide single access to something.
* Usage:
* In your class add:
*
* CSema4 m_MySema4;
*
* When you need protected access:
*
* Locker myLock(m_MySema4); -- constructor
* {
* -- protected stuff goes here
* } -- implied destructor
*
* Bracket placement is important:
* Locker: constructor locks, destructor unlocks.
*/
class CSema4
{
public:
CSema4();
void Lock();
void Unlock();
private:
SemaphoreHandle_t m_Sem;
StaticSemaphore_t m_Buf;
};
class Locker
{
public:
Locker(CSema4 & sema4) : m_Sema4(sema4) { m_Sema4.Lock(); }
~Locker() { m_Sema4.Unlock(); }
private:
CSema4 & m_Sema4;
};
#endif
Sema4.cpp
/* Sema4.cpp */
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "Sema4.h"
CSema4::CSema4()
{
m_Sem = xSemaphoreCreateBinaryStatic(&m_Buf);
xSemaphoreGive(m_Sem);
}
void CSema4::Lock()
{
xSemaphoreTake(m_Sem, portMAX_DELAY); /* Wait forever */
}
void CSema4::Unlock()
{
xSemaphoreGive(m_Sem);
}
Concurrency
-
MicroController
- Posts: 2661
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: Concurrency
For this case, consider using a (recursive) mutex instead of a binary semaphore. And note the restrictions for use inside an ISR context./*
* Handy class to provide single access to something.
Btw, you can also use C++ std::mutex and std::lock_guard with the IDF.
Who is online
Users browsing this forum: Bytespider, ChatGPT-User, Google [Bot], meta-externalagent, Semrush [Bot] and 18 guests