ZeroTierOne/node/Mutex.hpp

163 lines
2.3 KiB
C++
Raw Normal View History

/*
2019-08-23 16:23:39 +00:00
* Copyright (c)2019 ZeroTier, Inc.
*
2019-08-23 16:23:39 +00:00
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
2020-08-20 19:51:39 +00:00
* Change Date: 2025-01-01
*
2019-08-23 16:23:39 +00:00
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
2019-08-23 16:23:39 +00:00
/****/
#ifndef ZT_MUTEX_HPP
#define ZT_MUTEX_HPP
#include "Constants.hpp"
#ifdef __UNIX_LIKE__
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
namespace ZeroTier {
// libpthread based mutex lock
2018-01-27 02:34:56 +00:00
class Mutex
{
public:
Mutex()
{
pthread_mutex_init(&_mh,(const pthread_mutexattr_t *)0);
}
~Mutex()
{
pthread_mutex_destroy(&_mh);
}
inline void lock() const
{
2017-09-01 00:47:44 +00:00
pthread_mutex_lock(&((const_cast <Mutex *> (this))->_mh));
}
inline void unlock() const
{
2017-09-01 00:47:44 +00:00
pthread_mutex_unlock(&((const_cast <Mutex *> (this))->_mh));
}
2018-01-27 02:34:56 +00:00
class Lock
{
public:
2017-07-17 21:21:09 +00:00
Lock(Mutex &m) :
_m(&m)
{
m.lock();
}
2017-07-17 21:21:09 +00:00
Lock(const Mutex &m) :
_m(const_cast<Mutex *>(&m))
{
_m->lock();
}
~Lock()
{
_m->unlock();
}
private:
Mutex *const _m;
};
private:
2018-01-27 02:34:56 +00:00
Mutex(const Mutex &) {}
const Mutex &operator=(const Mutex &) { return *this; }
pthread_mutex_t _mh;
};
} // namespace ZeroTier
#endif
#ifdef __WINDOWS__
#include <stdlib.h>
#include <windows.h>
namespace ZeroTier {
// Windows critical section based lock
2018-01-27 02:34:56 +00:00
class Mutex
{
public:
Mutex()
{
InitializeCriticalSection(&_cs);
}
~Mutex()
{
DeleteCriticalSection(&_cs);
}
inline void lock()
{
EnterCriticalSection(&_cs);
}
inline void unlock()
{
LeaveCriticalSection(&_cs);
}
inline void lock() const
{
(const_cast <Mutex *> (this))->lock();
}
inline void unlock() const
{
(const_cast <Mutex *> (this))->unlock();
}
2018-01-27 02:34:56 +00:00
class Lock
{
public:
2017-07-17 21:21:09 +00:00
Lock(Mutex &m) :
_m(&m)
{
m.lock();
}
2017-07-17 21:21:09 +00:00
Lock(const Mutex &m) :
_m(const_cast<Mutex *>(&m))
{
_m->lock();
}
~Lock()
{
_m->unlock();
}
private:
Mutex *const _m;
};
private:
2018-01-27 02:34:56 +00:00
Mutex(const Mutex &) {}
const Mutex &operator=(const Mutex &) { return *this; }
CRITICAL_SECTION _cs;
};
} // namespace ZeroTier
#endif // _WIN32
#endif