summaryrefslogtreecommitdiffstats
path: root/src/core/hle/service/mutex.cpp
blob: 07589a0f0efe93574b7f20246e745a0634010938 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/core.h"
#include "core/hle/kernel/k_event.h"
#include "core/hle/kernel/k_synchronization_object.h"
#include "core/hle/service/mutex.h"

namespace Service {

Mutex::Mutex(Core::System& system) : m_system(system) {
    m_event = Kernel::KEvent::Create(system.Kernel());
    m_event->Initialize(nullptr);

    ASSERT(R_SUCCEEDED(m_event->Signal()));
}

Mutex::~Mutex() {
    m_event->GetReadableEvent().Close();
    m_event->Close();
}

void Mutex::lock() {
    // Infinitely retry until we successfully clear the event.
    while (R_FAILED(m_event->GetReadableEvent().Reset())) {
        s32 index;
        Kernel::KSynchronizationObject* obj = &m_event->GetReadableEvent();

        // The event was already cleared!
        // Wait for it to become signaled again.
        ASSERT(R_SUCCEEDED(
            Kernel::KSynchronizationObject::Wait(m_system.Kernel(), &index, &obj, 1, -1)));
    }

    // We successfully cleared the event, and now have exclusive ownership.
}

void Mutex::unlock() {
    // Unlock.
    ASSERT(R_SUCCEEDED(m_event->Signal()));
}

} // namespace Service