Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Added threading to AJM #1460

Merged
merged 1 commit into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions src/common/indexed_resources.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <boost/icl/interval_set.hpp>

#include <limits>
#include <optional>
#include <shared_mutex>
#include <unordered_map>

#include <memory>

namespace Common {

template <class Index, class T, Index MaxIndex = std::numeric_limits<Index>::max()>
class IndexedResources {
public:
IndexedResources() {
m_free_indices += boost::icl::interval<Index>::closed(0, MaxIndex);
}

template <class... Types>
std::optional<Index> Create(Types&&... args) {
std::unique_lock lock{m_mutex};
if (m_free_indices.empty()) {
return {};
}
auto index = first(*m_free_indices.begin());
m_free_indices -= index;
m_container.emplace(index, T(std::forward<Types>(args)...));
return index;
}

void Destroy(Index index) {
std::unique_lock lock{m_mutex};
if (m_container.erase(index) > 0) {
m_free_indices += index;
}
}

std::optional<std::reference_wrapper<T>> Get(Index index) {
std::shared_lock lock{m_mutex};
auto it = m_container.find(index);
if (it == m_container.end()) {
return {};
}
return it->second;
}

private:
std::shared_mutex m_mutex;
std::unordered_map<Index, T> m_container;
boost::icl::interval_set<Index> m_free_indices;
};

} // namespace Common
Loading
Loading