基质喷涂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

71 lines
2.1 KiB

#include "mutex.hpp"
#define TAG "zmutex"
using namespace iflytop;
/*******************************************************************************
* zmutex *
*******************************************************************************/
#if 0
zmutex::zmutex(const char* name) { this->name = name; }
zmutex::~zmutex() { vSemaphoreDelete(recursiveMutex); }
void zmutex::init() {
recursiveMutex = xSemaphoreCreateRecursiveMutex();
ZASSERT_INFO(recursiveMutex != NULL, "zmutex (%s) init failed", name);
}
bool zmutex::isInit() { return recursiveMutex != NULL; }
void zmutex::lock() {
// ZASSERT(recursiveMutex != NULL);
ZASSERT_INFO(recursiveMutex != NULL, "zmutex (%s) not init, init it", name);
xSemaphoreTakeRecursive(recursiveMutex, portMAX_DELAY);
}
void zmutex::unlock() { xSemaphoreGiveRecursive(recursiveMutex); }
/*******************************************************************************
* zlock_guard *
*******************************************************************************/
zlock_guard::zlock_guard(zmutex& mutex) : m_mutex(mutex) { m_mutex.lock(); }
zlock_guard::~zlock_guard() { m_mutex.unlock(); }
#else
zmutex::zmutex(const char* name) {
// 为了避免悬空指针,这里使用strdup复制字符串
this->name = name? strdup(name) : nullptr;
}
zmutex::~zmutex() {
if (recursiveMutex!= nullptr) {
vQueueDelete(recursiveMutex);
}
if (name!= nullptr) {
free((void*)name);
}
}
void zmutex::init() {
recursiveMutex = xSemaphoreCreateRecursiveMutex();
ZASSERT_INFO(recursiveMutex!= NULL, "zmutex (%s) init failed", name);
}
bool zmutex::isInit() {
return recursiveMutex!= NULL;
}
void zmutex::lock() {
ZASSERT_INFO(recursiveMutex!= NULL, "zmutex (%s) not init, init it", name);
xSemaphoreTakeRecursive(recursiveMutex, portMAX_DELAY);
}
void zmutex::unlock() {
xSemaphoreGiveRecursive(recursiveMutex);
}
zlock_guard::zlock_guard(zmutex& mutex) : m_mutex(mutex) {
m_mutex.lock();
}
zlock_guard::~zlock_guard() {
m_mutex.unlock();
}
#endif