Last active
April 16, 2019 14:44
-
-
Save yni3/cdc3e28e8da8adf540f65eb9baf52d99 to your computer and use it in GitHub Desktop.
Mutex using C++11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
SimpleMutex.cpp -- implement for SimpleMutex.h | |
Copyright 2018 yni3 | |
License : Public Domain (useful for copy and paste for your project) | |
*/ | |
#include "SimpleMutex.h" | |
#include <mutex> | |
#include <utility> | |
using namespace yni3; | |
struct SimpleLockHolder::Implemants | |
{ | |
std::lock_guard<std::mutex> lock; | |
Implemants( std::mutex& m ) | |
: lock( m ) | |
{ | |
} | |
~Implemants() | |
{ | |
} | |
}; | |
struct SimpleMutex::Implemants | |
{ | |
std::mutex mtx_; | |
}; | |
//------------------------------------------------------- | |
SimpleLockHolder::SimpleLockHolder( SimpleMutex* p ) | |
: m_pSelf( new Implemants( p->m_pSelf->mtx_ ) ) | |
{ | |
} | |
SimpleLockHolder::~SimpleLockHolder() | |
{ | |
if( m_pSelf ) | |
{ | |
delete m_pSelf; | |
} | |
} | |
SimpleLockHolder::SimpleLockHolder( SimpleLockHolder&& a ) noexcept | |
{ | |
m_pSelf = a.m_pSelf; | |
a.m_pSelf = nullptr; | |
} | |
//------------------------------------------------------- | |
SimpleMutex::SimpleMutex() | |
: m_pSelf( new Implemants() ) | |
{ | |
} | |
SimpleMutex::~SimpleMutex() | |
{ | |
delete m_pSelf; | |
} | |
SimpleLockHolder SimpleMutex::CreateLock() | |
{ | |
SimpleLockHolder lock( this ); | |
return std::move( lock ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
SimpleMutex.h -- [C++11] simple use for mutex | |
Copyright 2018 yni3 | |
License : Public Domain (useful for copy and paste for your project) | |
*/ | |
#ifndef __SIMPLEMUTEX | |
#define __SIMPLEMUTEX | |
namespace yni3 | |
{ | |
class SimpleMutex; | |
//mutex lock hold object | |
//unlock when delete object | |
class SimpleLockHolder | |
{ | |
friend class SimpleMutex; | |
SimpleLockHolder( SimpleMutex* ); | |
public: | |
~SimpleLockHolder(); | |
SimpleLockHolder( const SimpleLockHolder& a ) = delete; | |
SimpleLockHolder( SimpleLockHolder&& a ) noexcept; | |
private: | |
struct Implemants; | |
Implemants* m_pSelf; | |
}; | |
//mutex lock creator | |
class SimpleMutex | |
{ | |
friend class SimpleLockHolder; | |
public: | |
SimpleMutex(); | |
~SimpleMutex(); | |
SimpleMutex( const SimpleMutex& a ) = delete; | |
SimpleMutex( SimpleMutex&& a ) = delete; | |
SimpleLockHolder CreateLock(); | |
private: | |
struct Implemants; | |
Implemants* m_pSelf; | |
}; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment