From 5735014afeee488dfa2173f7c0b8b2b7ae301c8a Mon Sep 17 00:00:00 2001 From: hehongzhe <935062458@qq.com> Date: Fri, 29 Aug 2025 16:24:13 +0800 Subject: [PATCH] fix thread gil --- torch_npu/csrc/profiler/profiler_python.cpp | 22 +++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/torch_npu/csrc/profiler/profiler_python.cpp b/torch_npu/csrc/profiler/profiler_python.cpp index cba33f749d..2f6c1e774d 100644 --- a/torch_npu/csrc/profiler/profiler_python.cpp +++ b/torch_npu/csrc/profiler/profiler_python.cpp @@ -216,6 +216,7 @@ public: private: PythonTracer(); static PythonTracer& singleton(); + static PythonTracer* get_singleton_in_child_thread(); void start(size_t max_threads = max_py_threads); void startOne(); @@ -248,14 +249,27 @@ private: AppendOnlyList events_; std::unordered_map> start_py_call_info_; std::unordered_map ctx_tid_map_; + static std::atomic instance_created_; }; +std::atomic torch_npu::profiler::python_tracer::PythonTracer::instance_created_ = false; + PythonTracer& PythonTracer::singleton() { static PythonTracer singleton_; + instance_created_ = true; return singleton_; } +PythonTracer* PythonTracer::get_singleton_in_child_thread() +{ + if (instance_created_) { + return &singleton(); + } else { + return nullptr; + } +} + PythonTracer::PythonTracer() : active_(false) { pybind11::gil_scoped_acquire gil; @@ -673,7 +687,9 @@ void PythonTracer::call(Command c) { switch (c) { case Command::kStartOne: - PythonTracer::singleton().startOne(); + if (auto tracer = get_singleton_in_child_thread()) { + tracer->startOne(); + } break; case Command::kStartAll: @@ -685,7 +701,9 @@ void PythonTracer::call(Command c) break; case Command::kStopOne: - PythonTracer::singleton().stopOne(); + if (auto tracer = get_singleton_in_child_thread()) { + tracer->stopOne(); + } break; case Command::kClear: -- Gitee