pytorch/torch/csrc/monitor/events.cpp
Joe Wang 451c233936 leaking c++ singleton specifically (#143509)
Summary:
fix forward for S477887

leaking c++ singleton specifically

when c++ shutdown, it tries to destruct the singleton and acquire GIL, at this moment python runtime exists already, causing undefined behavior.
Leaking here specifically so that we won't try to destroy singleton at the shutdown phase

Test Plan: n/a

Differential Revision: D67400633

Pull Request resolved: https://github.com/pytorch/pytorch/pull/143509
Approved by: https://github.com/c-p-i-o
2024-12-19 09:27:07 +00:00

58 lines
1.3 KiB
C++

#include <torch/csrc/monitor/events.h>
#include <algorithm>
#include <mutex>
#include <vector>
namespace torch::monitor {
namespace {
class EventHandlers {
public:
void registerEventHandler(std::shared_ptr<EventHandler> handler) noexcept {
std::unique_lock<std::mutex> lock(mu_);
handlers_.emplace_back(std::move(handler));
}
void unregisterEventHandler(
const std::shared_ptr<EventHandler>& handler) noexcept {
std::unique_lock<std::mutex> lock(mu_);
auto it = std::find(handlers_.begin(), handlers_.end(), handler);
handlers_.erase(it);
}
void logEvent(const Event& e) {
std::unique_lock<std::mutex> lock(mu_);
for (auto& handler : handlers_) {
handler->handle(e);
}
}
static EventHandlers& get() noexcept {
static auto ehsPtr = new EventHandlers();
return *ehsPtr;
}
private:
std::mutex mu_{};
std::vector<std::shared_ptr<EventHandler>> handlers_{};
};
} // namespace
void logEvent(const Event& e) {
EventHandlers::get().logEvent(e);
}
void registerEventHandler(std::shared_ptr<EventHandler> p) {
EventHandlers::get().registerEventHandler(std::move(p));
}
void unregisterEventHandler(const std::shared_ptr<EventHandler>& p) {
EventHandlers::get().unregisterEventHandler(p);
}
} // namespace torch::monitor