SimpleKernel 1.17.0
Loading...
Searching...
No Matches
mutex.hpp
Go to the documentation of this file.
1
5#pragma once
6
7#include <atomic>
8#include <cstddef>
9#include <cstdint>
10#include <limits>
11
12#include "expected.hpp"
13#include "resource_id.hpp"
15
30class Mutex {
31 public:
33 const char* name{"unnamed_mutex"};
34
43 [[nodiscard]] auto Lock() -> Expected<void>;
44
53 [[nodiscard]] auto UnLock() -> Expected<void>;
54
62 [[nodiscard]] auto TryLock() -> Expected<void>;
63
69 [[nodiscard]] auto IsLockedByCurrentTask() const -> bool;
70
73 explicit Mutex(const char* _name)
74 : name(_name),
75 resource_id_(ResourceType::kMutex, reinterpret_cast<uint64_t>(this)) {}
76 Mutex() = default;
77
78 Mutex(const Mutex&) = delete;
79 Mutex(Mutex&&) = delete;
80 auto operator=(const Mutex&) -> Mutex& = delete;
81 auto operator=(Mutex&&) -> Mutex& = delete;
82 ~Mutex() = default;
84
85 protected:
87 std::atomic<bool> locked_{false};
88
90 std::atomic<Pid> owner_{std::numeric_limits<Pid>::max()};
91
94};
互斥锁(Mutex)
Definition mutex.hpp:30
Mutex(const Mutex &)=delete
const char * name
锁的名称
Definition mutex.hpp:33
std::atomic< Pid > owner_
持有锁的任务 ID,max() 表示未被持有
Definition mutex.hpp:90
Mutex(Mutex &&)=delete
Mutex()=default
ResourceId resource_id_
资源 ID,用于任务阻塞队列
Definition mutex.hpp:93
auto operator=(const Mutex &) -> Mutex &=delete
auto Lock() -> Expected< void >
获取锁(阻塞)
Definition mutex.cpp:11
auto IsLockedByCurrentTask() const -> bool
检查锁是否被当前线程持有
Definition mutex.cpp:99
auto operator=(Mutex &&) -> Mutex &=delete
auto UnLock() -> Expected< void >
释放锁
Definition mutex.cpp:41
std::atomic< bool > locked_
锁状态
Definition mutex.hpp:87
auto TryLock() -> Expected< void >
尝试获取锁(非阻塞)
Definition mutex.cpp:68
~Mutex()=default
资源 ID
std::expected< T, Error > Expected
std::expected 别名模板
Definition expected.hpp:365
ResourceType
资源类型枚举
@ kMutex
互斥锁