* Copyright (c) 2024 Huawei Technologies Co., Ltd.
* openUBMC is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "mc/singleton.h"
#include <algorithm>
#include <iostream>
namespace mc {
singleton_manager& singleton_manager::instance() {
static singleton_manager instance;
return instance;
}
singleton_manager::~singleton_manager() {
destroy_instances();
}
void singleton_manager::register_singleton(
const type_key_t& key,
destroy_fn_t destroy_fn,
bool leaky
) {
std::lock_guard<std::mutex> lock(m_mutex);
if (!leaky) {
m_non_leaky_instances[key] = std::move(destroy_fn);
}
}
void singleton_manager::destroy_instances() {
std::lock_guard<std::mutex> lock(m_mutex);
for (const auto& kv : m_non_leaky_instances) {
m_destroy_queue.push_back(kv.second);
}
m_non_leaky_instances.clear();
for (auto it = m_destroy_queue.rbegin(); it != m_destroy_queue.rend(); ++it) {
try {
(*it)();
} catch (const std::exception& e) {
std::cerr << "[singleton] Warning: Exception during singleton destruction: "
<< e.what() << std::endl;
} catch (...) {
std::cerr << "[singleton] Warning: Unknown exception during singleton destruction"
<< std::endl;
}
}
m_destroy_queue.clear();
}
void singleton_manager::reset_for_test() {
destroy_instances();
std::lock_guard<std::mutex> lock(m_mutex);
m_non_leaky_instances.clear();
m_destroy_queue.clear();
}
}