| 99 | } |
| 100 | |
| 101 | auto Mutex::TryLock() -> Expected<void> { |
| 102 | auto current_task = TaskManagerSingleton::instance().GetCurrentTask(); |
| 103 | if (current_task == nullptr) { |
| 104 | klog::Err("Mutex::TryLock: Cannot trylock mutex '{}' outside task context", |
| 105 | name); |
| 106 | return std::unexpected(Error{ErrorCode::kMutexNoTaskContext}); |
| 107 | } |
| 108 | |
| 109 | Pid current_pid = current_task->pid; |
| 110 | |
| 111 | if (IsLockedByCurrentTask()) { |
| 112 | klog::Debug( |
| 113 | "Mutex::TryLock: Task {} tried to recursively trylock mutex '{}'", |
| 114 | current_pid, name); |
| 115 | return std::unexpected(Error{ErrorCode::kMutexRecursiveLock}); |
| 116 | } |
| 117 | |
| 118 | bool expected = false; |
| 119 | if (locked_.compare_exchange_strong(expected, true, std::memory_order_acquire, |
| 120 | std::memory_order_relaxed)) { |
| 121 | owner_.store(current_pid, std::memory_order_release); |
| 122 | klog::Debug("Mutex::TryLock: Task {} acquired mutex '{}'", current_pid, |
| 123 | name); |
| 124 | return {}; |
| 125 | } |
| 126 | |
| 127 | klog::Debug("Mutex::TryLock: Task {} failed to acquire mutex '{}'", |
| 128 | current_pid, name); |
| 129 | return std::unexpected(Error{ErrorCode::kMutexNotLocked}); |
| 130 | } |
| 131 | |
| 132 | auto Mutex::IsLockedByCurrentTask() const -> bool { |
| 133 | auto current_task = TaskManagerSingleton::instance().GetCurrentTask(); |