2018-10-23 21:32:53 +00:00
|
|
|
#pragma once
|
|
|
|
|
2019-03-16 12:18:22 +00:00
|
|
|
#include <AK/Assertions.h>
|
2019-10-12 17:17:34 +00:00
|
|
|
#include <AK/Atomic.h>
|
2019-12-01 10:57:20 +00:00
|
|
|
#include <AK/Types.h>
|
2019-06-07 18:02:01 +00:00
|
|
|
#include <Kernel/Arch/i386/CPU.h>
|
2019-05-14 09:50:15 +00:00
|
|
|
#include <Kernel/KSyms.h>
|
2019-05-28 09:53:16 +00:00
|
|
|
#include <Kernel/Scheduler.h>
|
2019-12-01 10:57:20 +00:00
|
|
|
#include <Kernel/WaitQueue.h>
|
2019-01-16 15:03:50 +00:00
|
|
|
|
2019-03-23 21:03:17 +00:00
|
|
|
class Thread;
|
|
|
|
extern Thread* current;
|
2019-01-16 15:03:50 +00:00
|
|
|
|
2019-01-17 15:25:02 +00:00
|
|
|
class Lock {
|
2018-10-23 21:32:53 +00:00
|
|
|
public:
|
2019-05-28 09:53:16 +00:00
|
|
|
Lock(const char* name = nullptr)
|
|
|
|
: m_name(name)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
~Lock() {}
|
2018-10-23 21:32:53 +00:00
|
|
|
|
2019-01-16 15:03:50 +00:00
|
|
|
void lock();
|
|
|
|
void unlock();
|
2019-04-01 18:02:05 +00:00
|
|
|
bool unlock_if_locked();
|
2019-12-26 10:43:23 +00:00
|
|
|
bool is_locked() const { return m_holder; }
|
2018-10-23 21:32:53 +00:00
|
|
|
|
2019-02-07 10:12:23 +00:00
|
|
|
const char* name() const { return m_name; }
|
|
|
|
|
2018-10-23 21:32:53 +00:00
|
|
|
private:
|
2019-10-12 17:17:34 +00:00
|
|
|
Atomic<bool> m_lock { false };
|
2019-07-03 19:17:35 +00:00
|
|
|
u32 m_level { 0 };
|
2019-03-23 21:03:17 +00:00
|
|
|
Thread* m_holder { nullptr };
|
2019-02-07 10:12:23 +00:00
|
|
|
const char* m_name { nullptr };
|
2019-12-01 10:57:20 +00:00
|
|
|
WaitQueue m_queue;
|
2018-10-23 21:32:53 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
class Locker {
|
|
|
|
public:
|
2019-05-28 09:53:16 +00:00
|
|
|
[[gnu::always_inline]] inline explicit Locker(Lock& l)
|
|
|
|
: m_lock(l)
|
|
|
|
{
|
|
|
|
lock();
|
|
|
|
}
|
2019-02-20 12:09:59 +00:00
|
|
|
[[gnu::always_inline]] inline ~Locker() { unlock(); }
|
|
|
|
[[gnu::always_inline]] inline void unlock() { m_lock.unlock(); }
|
|
|
|
[[gnu::always_inline]] inline void lock() { m_lock.lock(); }
|
2018-10-23 21:32:53 +00:00
|
|
|
|
|
|
|
private:
|
2019-01-17 15:25:02 +00:00
|
|
|
Lock& m_lock;
|
2018-10-23 21:32:53 +00:00
|
|
|
};
|
|
|
|
|
2019-01-16 15:03:50 +00:00
|
|
|
#define LOCKER(lock) Locker locker(lock)
|
2018-10-29 20:54:11 +00:00
|
|
|
|
2019-02-08 08:46:13 +00:00
|
|
|
template<typename T>
|
|
|
|
class Lockable {
|
|
|
|
public:
|
2019-05-28 09:53:16 +00:00
|
|
|
Lockable() {}
|
|
|
|
Lockable(T&& resource)
|
|
|
|
: m_resource(move(resource))
|
|
|
|
{
|
|
|
|
}
|
2019-02-08 08:46:13 +00:00
|
|
|
Lock& lock() { return m_lock; }
|
|
|
|
T& resource() { return m_resource; }
|
|
|
|
|
2019-02-08 15:18:24 +00:00
|
|
|
T lock_and_copy()
|
|
|
|
{
|
|
|
|
LOCKER(m_lock);
|
|
|
|
return m_resource;
|
|
|
|
}
|
|
|
|
|
2019-02-08 08:46:13 +00:00
|
|
|
private:
|
|
|
|
T m_resource;
|
|
|
|
Lock m_lock;
|
|
|
|
};
|