libxr
Embedded C++ framework for bare-metal, RTOS and Linux
Loading...
Searching...
No Matches
mutex.cpp
1#include "mutex.hpp"
2
3#include <pthread.h>
4
5#include <cerrno>
6
7#include "libxr_def.hpp"
8#include "libxr_system.hpp"
9
10using namespace LibXR;
11
12Mutex::Mutex() : mutex_handle_(PTHREAD_MUTEX_INITIALIZER) {}
13
14Mutex::~Mutex() { pthread_mutex_destroy(&mutex_handle_); }
15
17{
18 const int ans = pthread_mutex_lock(&mutex_handle_);
19 if (ans != 0)
20 {
21 return ErrorCode::FAILED;
22 }
23 return ErrorCode::OK;
24}
25
27{
28 const int ans = pthread_mutex_trylock(&mutex_handle_);
29 if (ans == EBUSY)
30 {
31 return ErrorCode::BUSY;
32 }
33 if (ans != 0)
34 {
35 return ErrorCode::FAILED;
36 }
37 return ErrorCode::OK;
38}
39
40void Mutex::Unlock() { pthread_mutex_unlock(&mutex_handle_); }
Mutex()
构造函数,初始化互斥锁 Constructor to initialize the mutex.
Definition mutex.cpp:12
ErrorCode Lock()
加锁,如果锁已被占用,则阻塞等待 Lock the mutex, blocking if it is already locked.
Definition mutex.cpp:16
ErrorCode TryLock()
尝试加锁,如果锁已被占用,则立即返回失败 Attempt to lock the mutex, returning immediately if already locked.
Definition mutex.cpp:26
~Mutex()
析构函数,销毁互斥锁 Destructor to destroy the mutex.
Definition mutex.cpp:14
void Unlock()
解锁互斥锁 Unlock the mutex.
Definition mutex.cpp:40
LibXR 命名空间 / LibXR namespace.
Definition ch32_can.hpp:14
ErrorCode
定义错误码枚举 / Defines an enumeration for error codes
@ BUSY
忙碌 / Busy
@ FAILED
操作失败 / Operation failed
@ OK
操作成功 / Operation successful