diff options
author | crupest <crupest@outlook.com> | 2021-06-10 11:12:25 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2021-06-10 11:12:25 +0800 |
commit | ef593ba2d445af515214d63bfd3942be9d673467 (patch) | |
tree | 6f286d3c30af2a6c74a1a60047fa25bae09fd9db /works/life/operating-system-experiment/Mutex.cpp | |
parent | 93d8feccd79b35fc890fc8629d6da2c2baa57762 (diff) | |
download | crupest-ef593ba2d445af515214d63bfd3942be9d673467.tar.gz crupest-ef593ba2d445af515214d63bfd3942be9d673467.tar.bz2 crupest-ef593ba2d445af515214d63bfd3942be9d673467.zip |
import(life): ...
Diffstat (limited to 'works/life/operating-system-experiment/Mutex.cpp')
-rw-r--r-- | works/life/operating-system-experiment/Mutex.cpp | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/works/life/operating-system-experiment/Mutex.cpp b/works/life/operating-system-experiment/Mutex.cpp new file mode 100644 index 0000000..6a91885 --- /dev/null +++ b/works/life/operating-system-experiment/Mutex.cpp @@ -0,0 +1,78 @@ +#include "Mutex.h" + +#include <cassert> +#include <pthread.h> + +#ifndef CRU_WINDOWS +#include <errno.h> +#endif + +namespace cru { +Mutex::Mutex() { +#ifdef CRU_WINDOWS +#else + mutex_ = std::make_unique<pthread_mutex_t>(); + + auto c = pthread_mutex_init(mutex_.get(), nullptr); + assert(c == 0); +#endif +} + +Mutex::Mutex(Mutex &&other) +#ifdef CRU_WINDOWS +#else + : mutex_(std::move(other.mutex_)) +#endif +{ +} + +Mutex &Mutex::operator=(Mutex &&other) { + if (this != &other) { + Destroy(); + mutex_ = std::move(other.mutex_); + } + return *this; +} + +Mutex::~Mutex() { Destroy(); } + +void Mutex::Lock() { +#ifdef CRU_WINDOWS +#else + assert(mutex_); + auto c = pthread_mutex_lock(mutex_.get()); + assert(c == 0); +#endif +} + +bool Mutex::TryLock() { +#ifdef CRU_WINDOWS +#else + assert(mutex_); + auto c = pthread_mutex_trylock(mutex_.get()); + assert(c == 0 || c == EBUSY); + return c == 0 ? true : false; +#endif +} + +void Mutex::Unlock() { +#ifdef CRU_WINDOWS +#else + assert(mutex_); + auto c = pthread_mutex_unlock(mutex_.get()); + assert(c == 0); +#endif +} + +void Mutex::Destroy() { +#ifdef CRU_WINDOWS +#else + if (mutex_ != nullptr) { + auto c = pthread_mutex_destroy(mutex_.get()); + assert(c); + mutex_ = nullptr; + } +#endif +} + +} // namespace cru |