• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
6 #define BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
7 
8 #include <map>
9 #include <string>
10 
11 #include "base/base_export.h"
12 #include "base/callback.h"
13 #include "base/macros.h"
14 #include "base/synchronization/lock.h"
15 #include "base/threading/platform_thread.h"
16 
17 namespace base {
18 
19 template <typename T>
20 struct DefaultSingletonTraits;
21 
22 class BASE_EXPORT ThreadIdNameManager {
23  public:
24   static ThreadIdNameManager* GetInstance();
25 
26   static const char* GetDefaultInternedString();
27 
28   // Register the mapping between a thread |id| and |handle|.
29   void RegisterThread(PlatformThreadHandle::Handle handle, PlatformThreadId id);
30 
31   // The callback is called on the thread, immediately after the name is set.
32   // |name| is a pointer to a C string that is guaranteed to remain valid for
33   // the duration of the process.
34   using SetNameCallback = base::RepeatingCallback<void(const char* name)>;
35   void InstallSetNameCallback(SetNameCallback callback);
36 
37   // Set the name for the current thread.
38   void SetName(const std::string& name);
39 
40   // Get the name for the given id.
41   const char* GetName(PlatformThreadId id);
42 
43   // Unlike |GetName|, this method using TLS and avoids touching |lock_|.
44   const char* GetNameForCurrentThread();
45 
46   // Remove the name for the given id.
47   void RemoveName(PlatformThreadHandle::Handle handle, PlatformThreadId id);
48 
49  private:
50   friend struct DefaultSingletonTraits<ThreadIdNameManager>;
51 
52   typedef std::map<PlatformThreadId, PlatformThreadHandle::Handle>
53       ThreadIdToHandleMap;
54   typedef std::map<PlatformThreadHandle::Handle, std::string*>
55       ThreadHandleToInternedNameMap;
56   typedef std::map<std::string, std::string*> NameToInternedNameMap;
57 
58   ThreadIdNameManager();
59   ~ThreadIdNameManager();
60 
61   // lock_ protects the name_to_interned_name_, thread_id_to_handle_ and
62   // thread_handle_to_interned_name_ maps.
63   Lock lock_;
64 
65   NameToInternedNameMap name_to_interned_name_;
66   ThreadIdToHandleMap thread_id_to_handle_;
67   ThreadHandleToInternedNameMap thread_handle_to_interned_name_;
68 
69   // Treat the main process specially as there is no PlatformThreadHandle.
70   std::string* main_process_name_;
71   PlatformThreadId main_process_id_;
72 
73   SetNameCallback set_name_callback_;
74 
75   DISALLOW_COPY_AND_ASSIGN(ThreadIdNameManager);
76 };
77 
78 }  // namespace base
79 
80 #endif  // BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
81