thread_name.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "thread_name.h"
  2. #include <library/cpp/yt/misc/tls.h>
  3. #include <util/generic/string.h>
  4. #include <util/system/thread.h>
  5. #include <algorithm>
  6. #include <cstring>
  7. namespace NYT {
  8. ////////////////////////////////////////////////////////////////////////////////
  9. TStringBuf TThreadName::ToStringBuf() const
  10. {
  11. // Buffer is zero terminated.
  12. return TStringBuf(Buffer.data(), Length);
  13. }
  14. ////////////////////////////////////////////////////////////////////////////////
  15. TThreadName::TThreadName(const TString& name)
  16. {
  17. Length = std::min<int>(TThreadName::BufferCapacity - 1, name.length());
  18. ::memcpy(Buffer.data(), name.data(), Length);
  19. }
  20. ////////////////////////////////////////////////////////////////////////////////
  21. // This function uses cached TThread::CurrentThreadName() result
  22. TThreadName GetCurrentThreadName()
  23. {
  24. static YT_THREAD_LOCAL(TThreadName) ThreadName;
  25. auto& threadName = GetTlsRef(ThreadName);
  26. if (threadName.Length == 0) {
  27. if (auto name = TThread::CurrentThreadName()) {
  28. auto length = std::min<int>(TThreadName::BufferCapacity - 1, name.length());
  29. threadName.Length = length;
  30. ::memcpy(threadName.Buffer.data(), name.data(), length);
  31. }
  32. }
  33. return threadName;
  34. }
  35. ////////////////////////////////////////////////////////////////////////////////
  36. } // namespace NYT