diff --git a/torch_npu/csrc/profiler/profiler_python.cpp b/torch_npu/csrc/profiler/profiler_python.cpp index cba33f749d483ed59d62c740e86f5c6088f4f68c..2f6c1e774d1572277f44104e0a75563c0b6be1cc 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: