ddnet/src/base/tl/threading.h

72 lines
1.1 KiB
C
Raw Normal View History

#ifndef BASE_TL_THREADING_H
#define BASE_TL_THREADING_H
#include "../system.h"
2021-12-07 12:18:04 +00:00
#include <atomic>
class CSemaphore
{
SEMAPHORE m_Sem;
2021-12-07 12:18:04 +00:00
// implement the counter seperatly, because the `sem_getvalue`-API is
// deprecated on macOS: https://stackoverflow.com/a/16655541
std::atomic_int count;
public:
CSemaphore() { sphore_init(&m_Sem); }
~CSemaphore() { sphore_destroy(&m_Sem); }
CSemaphore(const CSemaphore &) = delete;
2021-12-07 12:18:04 +00:00
int GetApproximateValue() { return count.load(); }
void Wait()
{
sphore_wait(&m_Sem);
count.fetch_sub(1);
}
void Signal()
{
count.fetch_add(1);
sphore_signal(&m_Sem);
}
};
class SCOPED_CAPABILITY CLock
{
LOCK m_Lock;
public:
CLock() ACQUIRE(m_Lock)
{
m_Lock = lock_create();
}
~CLock() RELEASE()
{
lock_destroy(m_Lock);
}
2018-08-27 12:49:17 +00:00
CLock(const CLock &) = delete;
2018-08-29 09:13:13 +00:00
void Take() ACQUIRE(m_Lock) { lock_wait(m_Lock); }
void Release() RELEASE() { lock_unlock(m_Lock); }
};
class CScopeLock
{
CLock *m_pLock;
public:
CScopeLock(CLock *pLock)
{
m_pLock = pLock;
m_pLock->Take();
}
~CScopeLock()
{
m_pLock->Release();
}
2018-08-29 09:13:13 +00:00
CScopeLock(const CScopeLock &) = delete;
};
#endif // BASE_TL_THREADING_H