thread_id_name_manager.h 2.01 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#ifndef BUTIL_THREADING_THREAD_ID_NAME_MANAGER_H_
#define BUTIL_THREADING_THREAD_ID_NAME_MANAGER_H_
gejun's avatar
gejun committed
7 8 9 10

#include <map>
#include <string>

11 12 13 14
#include "butil/base_export.h"
#include "butil/basictypes.h"
#include "butil/synchronization/lock.h"
#include "butil/threading/platform_thread.h"
gejun's avatar
gejun committed
15 16 17

template <typename T> struct DefaultSingletonTraits;

18
namespace butil {
gejun's avatar
gejun committed
19

20
class BUTIL_EXPORT ThreadIdNameManager {
gejun's avatar
gejun committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 public:
  static ThreadIdNameManager* GetInstance();

  static const char* GetDefaultInternedString();

  // Register the mapping between a thread |id| and |handle|.
  void RegisterThread(PlatformThreadHandle::Handle handle, PlatformThreadId id);

  // Set the name for the given id.
  void SetName(PlatformThreadId id, const char* name);

  // Get the name for the given id.
  const char* GetName(PlatformThreadId id);

  // Remove the name for the given id.
  void RemoveName(PlatformThreadHandle::Handle handle, PlatformThreadId id);

 private:
  friend struct DefaultSingletonTraits<ThreadIdNameManager>;

  typedef std::map<PlatformThreadId, PlatformThreadHandle::Handle>
      ThreadIdToHandleMap;
  typedef std::map<PlatformThreadHandle::Handle, std::string*>
      ThreadHandleToInternedNameMap;
  typedef std::map<std::string, std::string*> NameToInternedNameMap;

  ThreadIdNameManager();
  ~ThreadIdNameManager();

  // lock_ protects the name_to_interned_name_, thread_id_to_handle_ and
  // thread_handle_to_interned_name_ maps.
  Lock lock_;

  NameToInternedNameMap name_to_interned_name_;
  ThreadIdToHandleMap thread_id_to_handle_;
  ThreadHandleToInternedNameMap thread_handle_to_interned_name_;

  // Treat the main process specially as there is no PlatformThreadHandle.
  std::string* main_process_name_;
  PlatformThreadId main_process_id_;

  DISALLOW_COPY_AND_ASSIGN(ThreadIdNameManager);
};

65
}  // namespace butil
gejun's avatar
gejun committed
66

67
#endif  // BUTIL_THREADING_THREAD_ID_NAME_MANAGER_H_