Skip to content

Instantly share code, notes, and snippets.

@yni3
Last active April 16, 2019 14:44
Show Gist options
  • Save yni3/cdc3e28e8da8adf540f65eb9baf52d99 to your computer and use it in GitHub Desktop.
Save yni3/cdc3e28e8da8adf540f65eb9baf52d99 to your computer and use it in GitHub Desktop.
Mutex using C++11
/*
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 );
}
/*
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