mutex.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "core/core.h"
  4. #include "core/hle/kernel/k_event.h"
  5. #include "core/hle/kernel/k_synchronization_object.h"
  6. #include "core/hle/service/mutex.h"
  7. namespace Service {
  8. Mutex::Mutex(Core::System& system) : m_system(system) {
  9. m_event = Kernel::KEvent::Create(system.Kernel());
  10. m_event->Initialize(nullptr);
  11. // Register the event.
  12. Kernel::KEvent::Register(system.Kernel(), m_event);
  13. ASSERT(R_SUCCEEDED(m_event->Signal()));
  14. }
  15. Mutex::~Mutex() {
  16. m_event->GetReadableEvent().Close();
  17. m_event->Close();
  18. }
  19. void Mutex::lock() {
  20. // Infinitely retry until we successfully clear the event.
  21. while (R_FAILED(m_event->GetReadableEvent().Reset())) {
  22. s32 index;
  23. Kernel::KSynchronizationObject* obj = &m_event->GetReadableEvent();
  24. // The event was already cleared!
  25. // Wait for it to become signaled again.
  26. ASSERT(R_SUCCEEDED(
  27. Kernel::KSynchronizationObject::Wait(m_system.Kernel(), &index, &obj, 1, -1)));
  28. }
  29. // We successfully cleared the event, and now have exclusive ownership.
  30. }
  31. void Mutex::unlock() {
  32. // Unlock.
  33. ASSERT(R_SUCCEEDED(m_event->Signal()));
  34. }
  35. } // namespace Service