12 auto current_task = TaskManagerSingleton::instance().GetCurrentTask();
13 if (current_task ==
nullptr) {
14 klog::Err(
"Mutex::Lock: Cannot lock mutex '{}' outside task context", name);
18 Pid current_pid = current_task->pid;
20 if (IsLockedByCurrentTask()) {
21 klog::Warn(
"Mutex::Lock: Task {} tried to recursively lock mutex '{}'",
26 bool expected =
false;
27 while (!locked_.compare_exchange_weak(
28 expected,
true, std::memory_order_acquire, std::memory_order_relaxed)) {
29 klog::Debug(
"Mutex::Lock: Task {} blocking on mutex '{}'", current_pid,
31 TaskManagerSingleton::instance().Block(resource_id_);
36 owner_.store(current_pid, std::memory_order_release);
37 klog::Debug(
"Mutex::Lock: Task {} acquired mutex '{}'", current_pid, name);
42 auto current_task = TaskManagerSingleton::instance().GetCurrentTask();
43 if (current_task ==
nullptr) {
44 klog::Err(
"Mutex::UnLock: Cannot unlock mutex '{}' outside task context",
49 Pid current_pid = current_task->pid;
51 if (!IsLockedByCurrentTask()) {
53 "Mutex::UnLock: Task {} tried to unlock mutex '{}' it doesn't own",
58 owner_.store(std::numeric_limits<Pid>::max(), std::memory_order_release);
59 locked_.store(
false, std::memory_order_release);
61 klog::Debug(
"Mutex::UnLock: Task {} released mutex '{}'", current_pid, name);
63 TaskManagerSingleton::instance().Wakeup(resource_id_);
69 auto current_task = TaskManagerSingleton::instance().GetCurrentTask();
70 if (current_task ==
nullptr) {
71 klog::Err(
"Mutex::TryLock: Cannot trylock mutex '{}' outside task context",
76 Pid current_pid = current_task->pid;
78 if (IsLockedByCurrentTask()) {
80 "Mutex::TryLock: Task {} tried to recursively trylock mutex '{}'",
85 bool expected =
false;
86 if (locked_.compare_exchange_strong(expected,
true, std::memory_order_acquire,
87 std::memory_order_relaxed)) {
88 owner_.store(current_pid, std::memory_order_release);
89 klog::Debug(
"Mutex::TryLock: Task {} acquired mutex '{}'", current_pid,
94 klog::Debug(
"Mutex::TryLock: Task {} failed to acquire mutex '{}'",
100 auto current_task = TaskManagerSingleton::instance().GetCurrentTask();
101 if (current_task ==
nullptr) {
105 return locked_.load(std::memory_order_acquire) &&
106 owner_.load(std::memory_order_acquire) == current_task->pid;
std::atomic< Pid > owner_
持有锁的任务 ID,max() 表示未被持有
auto Lock() -> Expected< void >
获取锁(阻塞)
auto IsLockedByCurrentTask() const -> bool
检查锁是否被当前线程持有
auto UnLock() -> Expected< void >
释放锁
std::atomic< bool > locked_
锁状态
auto TryLock() -> Expected< void >
尝试获取锁(非阻塞)
std::expected< T, Error > Expected
std::expected 别名模板
auto Err(etl::format_string< Args... > fmt, Args &&... args) -> void
以 ERROR 级别记录日志
auto Debug(etl::format_string< Args... > fmt, Args &&... args) -> void
以 DEBUG 级别记录日志(SIMPLEKERNEL_MIN_LOG_LEVEL > 0 时编译期消除)
auto Warn(etl::format_string< Args... > fmt, Args &&... args) -> void
以 WARN 级别记录日志