/* Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/phi/core/os_info.h" #include #include #include #include #if defined(__linux__) #include #include #include #elif defined(_MSC_VER) #include #else #include #endif #include "glog/logging.h" #include "paddle/phi/common/thread_data_registry.h" namespace phi { namespace internal { class InternalThreadId { public: InternalThreadId(); const ThreadId& GetTid() const { return id_; } private: ThreadId id_; }; InternalThreadId::InternalThreadId() { // C++ std tid id_.std_tid = std::hash()(std::this_thread::get_id()); // system tid #if defined(__linux__) id_.sys_tid = static_cast(syscall(SYS_gettid)); #elif defined(_MSC_VER) id_.sys_tid = static_cast(::GetCurrentThreadId()); #else // unsupported platforms, use std_tid id_.sys_tid = id_.std_tid; #endif // cupti tid std::stringstream ss; ss << std::this_thread::get_id(); id_.cupti_tid = static_cast(std::stoull(ss.str())); } } // namespace internal uint64_t GetCurrentThreadSysId() { return ThreadDataRegistry::GetInstance() .GetCurrentThreadData() .GetTid() .sys_tid; } uint64_t GetCurrentThreadStdId() { return ThreadDataRegistry::GetInstance() .GetCurrentThreadData() .GetTid() .std_tid; } ThreadId GetCurrentThreadId() { return ThreadDataRegistry::GetInstance() .GetCurrentThreadData() .GetTid(); } std::unordered_map GetAllThreadIds() { auto tids = ThreadDataRegistry::GetInstance() .GetAllThreadDataByValue(); std::unordered_map res; for (const auto& kv : tids) { res[kv.first] = kv.second.GetTid(); } return res; } std::string GetCurrentThreadName() { const auto& thread_name = ThreadDataRegistry::GetInstance().GetCurrentThreadData(); return thread_name.empty() ? kDefaultThreadName : thread_name; } std::unordered_map GetAllThreadNames() { return ThreadDataRegistry::GetInstance() .GetAllThreadDataByValue(); } bool SetCurrentThreadName(const std::string& name) { auto& instance = ThreadDataRegistry::GetInstance(); const auto& cur_name = instance.GetCurrentThreadData(); if (!cur_name.empty() || name.empty() || name == kDefaultThreadName) { return false; } instance.SetCurrentThreadData(name); VLOG(4) << __func__ << " " << name; return true; } uint32_t GetProcessId() { #if defined(_MSC_VER) return static_cast(GetCurrentProcessId()); #else return static_cast(getpid()); #endif } } // namespace phi