Files

159 lines
2.2 KiB
C++
Raw Permalink Normal View History

2025-08-06 12:10:18 -04:00
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
2025-08-06 12:10:18 -04:00
* (c) ZeroTier, Inc.
* https://www.zerotier.com/
*/
#ifndef ZT_MUTEX_HPP
#define ZT_MUTEX_HPP
#include "Constants.hpp"
#ifdef __UNIX_LIKE__
2025-07-03 11:26:23 -04:00
#include <pthread.h>
#include <stdlib.h>
namespace ZeroTier {
2017-08-23 18:52:32 -07:00
// libpthread based mutex lock
2025-07-03 11:26:23 -04:00
class Mutex {
public:
2017-08-23 18:52:32 -07:00
Mutex()
{
2025-07-03 11:26:23 -04:00
pthread_mutex_init(&_mh, (const pthread_mutexattr_t*)0);
2017-08-23 18:52:32 -07:00
}
~Mutex()
{
pthread_mutex_destroy(&_mh);
}
inline void lock() const
{
2025-07-03 11:26:23 -04:00
pthread_mutex_lock(&((const_cast<Mutex*>(this))->_mh));
2017-08-23 18:52:32 -07:00
}
inline void unlock() const
{
2025-07-03 11:26:23 -04:00
pthread_mutex_unlock(&((const_cast<Mutex*>(this))->_mh));
2017-08-23 18:52:32 -07:00
}
2025-07-03 11:26:23 -04:00
class Lock {
public:
Lock(Mutex& m) : _m(&m)
2017-08-23 18:52:32 -07:00
{
m.lock();
}
2025-07-03 11:26:23 -04:00
Lock(const Mutex& m) : _m(const_cast<Mutex*>(&m))
2017-08-23 18:52:32 -07:00
{
_m->lock();
}
~Lock()
{
_m->unlock();
}
2025-07-03 11:26:23 -04:00
private:
Mutex* const _m;
2017-08-23 18:52:32 -07:00
};
2025-07-03 11:26:23 -04:00
private:
Mutex(const Mutex&)
{
}
const Mutex& operator=(const Mutex&)
{
return *this;
}
2018-01-26 21:34:56 -05:00
pthread_mutex_t _mh;
};
2025-07-03 11:26:23 -04:00
} // namespace ZeroTier
#endif
#ifdef __WINDOWS__
#include <stdlib.h>
#include <windows.h>
namespace ZeroTier {
2017-08-23 18:52:32 -07:00
// Windows critical section based lock
2025-07-03 11:26:23 -04:00
class Mutex {
public:
Mutex()
{
InitializeCriticalSection(&_cs);
}
~Mutex()
{
DeleteCriticalSection(&_cs);
}
inline void lock()
{
EnterCriticalSection(&_cs);
}
inline void unlock()
{
LeaveCriticalSection(&_cs);
}
inline void lock() const
{
2025-07-03 11:26:23 -04:00
(const_cast<Mutex*>(this))->lock();
}
inline void unlock() const
{
2025-07-03 11:26:23 -04:00
(const_cast<Mutex*>(this))->unlock();
}
2025-07-03 11:26:23 -04:00
class Lock {
public:
Lock(Mutex& m) : _m(&m)
{
m.lock();
}
2025-07-03 11:26:23 -04:00
Lock(const Mutex& m) : _m(const_cast<Mutex*>(&m))
{
_m->lock();
}
~Lock()
{
_m->unlock();
}
2025-07-03 11:26:23 -04:00
private:
Mutex* const _m;
};
2025-07-03 11:26:23 -04:00
private:
Mutex(const Mutex&)
{
}
const Mutex& operator=(const Mutex&)
{
return *this;
}
2018-01-26 21:34:56 -05:00
CRITICAL_SECTION _cs;
};
2025-07-03 11:26:23 -04:00
} // namespace ZeroTier
2025-07-03 11:26:23 -04:00
#endif // _WIN32
#endif