2020-01-18 08:38:21 +00:00
|
|
|
/*
|
2021-07-05 20:56:54 +00:00
|
|
|
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
|
2020-01-18 08:38:21 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2019-03-25 12:03:49 +00:00
|
|
|
#pragma once
|
|
|
|
|
2021-04-28 10:26:36 +00:00
|
|
|
#include <AK/Assertions.h>
|
|
|
|
#include <AK/Types.h>
|
2021-07-05 20:56:54 +00:00
|
|
|
#include <pthread.h>
|
2019-03-25 12:03:49 +00:00
|
|
|
|
2021-05-22 16:47:42 +00:00
|
|
|
namespace Threading {
|
2019-08-25 20:51:27 +00:00
|
|
|
|
2021-07-09 09:14:57 +00:00
|
|
|
class Mutex {
|
2019-03-25 12:03:49 +00:00
|
|
|
public:
|
2021-07-09 09:14:57 +00:00
|
|
|
Mutex()
|
2021-07-05 22:14:19 +00:00
|
|
|
{
|
2021-07-05 22:06:32 +00:00
|
|
|
#ifndef __serenity__
|
2021-07-05 22:14:19 +00:00
|
|
|
pthread_mutexattr_t attr;
|
|
|
|
pthread_mutexattr_init(&attr);
|
|
|
|
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
|
|
|
pthread_mutex_init(&m_mutex, &attr);
|
2021-07-05 22:06:32 +00:00
|
|
|
#endif
|
|
|
|
}
|
2021-07-09 09:14:57 +00:00
|
|
|
~Mutex() { }
|
2019-03-25 12:03:49 +00:00
|
|
|
|
|
|
|
void lock();
|
|
|
|
void unlock();
|
|
|
|
|
|
|
|
private:
|
2021-07-05 22:06:32 +00:00
|
|
|
#ifdef __serenity__
|
2021-07-05 20:56:54 +00:00
|
|
|
pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
|
2021-07-05 22:06:32 +00:00
|
|
|
#else
|
|
|
|
pthread_mutex_t m_mutex;
|
|
|
|
#endif
|
2019-03-25 12:03:49 +00:00
|
|
|
};
|
|
|
|
|
2021-07-09 09:14:57 +00:00
|
|
|
class MutexLocker {
|
2019-03-25 12:03:49 +00:00
|
|
|
public:
|
2021-07-09 09:14:57 +00:00
|
|
|
ALWAYS_INLINE explicit MutexLocker(Mutex& mutex)
|
|
|
|
: m_mutex(mutex)
|
2019-05-28 09:53:16 +00:00
|
|
|
{
|
|
|
|
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(); }
|
2019-03-25 12:03:49 +00:00
|
|
|
|
|
|
|
private:
|
2021-07-09 09:14:57 +00:00
|
|
|
Mutex& m_mutex;
|
2019-03-25 12:03:49 +00:00
|
|
|
};
|
|
|
|
|
2021-07-09 09:14:57 +00:00
|
|
|
ALWAYS_INLINE void Mutex::lock()
|
2019-03-25 12:03:49 +00:00
|
|
|
{
|
2021-07-05 20:56:54 +00:00
|
|
|
pthread_mutex_lock(&m_mutex);
|
2019-03-25 12:03:49 +00:00
|
|
|
}
|
|
|
|
|
2021-07-09 09:14:57 +00:00
|
|
|
ALWAYS_INLINE void Mutex::unlock()
|
2019-03-25 12:03:49 +00:00
|
|
|
{
|
2021-07-05 20:56:54 +00:00
|
|
|
pthread_mutex_unlock(&m_mutex);
|
2019-03-25 12:03:49 +00:00
|
|
|
}
|
|
|
|
|
2019-08-25 20:51:27 +00:00
|
|
|
}
|