ladybird/Userland/Libraries/LibThreading/Mutex.h

67 lines
1.2 KiB
C
Raw Normal View History

/*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Assertions.h>
#include <AK/Types.h>
#include <pthread.h>
namespace Threading {
2021-07-09 09:14:57 +00:00
class Mutex {
friend class ConditionVariable;
public:
2021-07-09 09:14:57 +00:00
Mutex()
{
#ifndef __serenity__
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m_mutex, &attr);
#endif
}
2021-07-09 09:14:57 +00:00
~Mutex() { }
void lock();
void unlock();
private:
#ifdef __serenity__
pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
#else
pthread_mutex_t m_mutex;
#endif
};
2021-07-09 09:14:57 +00:00
class MutexLocker {
public:
2021-07-09 09:14:57 +00:00
ALWAYS_INLINE explicit MutexLocker(Mutex& mutex)
: m_mutex(mutex)
{
lock();
}
2021-07-09 09:14:57 +00:00
ALWAYS_INLINE ~MutexLocker() { unlock(); }
ALWAYS_INLINE void unlock() { m_mutex.unlock(); }
ALWAYS_INLINE void lock() { m_mutex.lock(); }
private:
2021-07-09 09:14:57 +00:00
Mutex& m_mutex;
};
2021-07-09 09:14:57 +00:00
ALWAYS_INLINE void Mutex::lock()
{
pthread_mutex_lock(&m_mutex);
}
2021-07-09 09:14:57 +00:00
ALWAYS_INLINE void Mutex::unlock()
{
pthread_mutex_unlock(&m_mutex);
}
}