1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "host/libs/confui/host_utils.h"
18
19 namespace cuttlefish {
20 namespace confui {
21 namespace thread {
Get(const std::thread::id tid)22 std::string ThreadTracer::Get(const std::thread::id tid) {
23 std::lock_guard<std::mutex> lock(mtx_);
24 if (Contains(id2name_, tid)) {
25 return id2name_[tid];
26 }
27 std::stringstream ss;
28 ss << "Thread@" << tid;
29 return ss.str();
30 }
31
Set(const std::string & name,const std::thread::id tid)32 void ThreadTracer::Set(const std::string& name, const std::thread::id tid) {
33 std::lock_guard<std::mutex> lock(mtx_);
34 if (Contains(name2id_, name)) {
35 // has the name already
36 if (name2id_[name] != tid) { // used for another thread
37 ConfUiLog(FATAL) << "Thread name is duplicated.";
38 }
39 // name and id are already set correctly
40 return;
41 }
42 if (Contains(id2name_, tid)) {
43 // tid exists but has a different name
44 name2id_.erase(id2name_[tid]); // delete old_name -> tid map
45 }
46 id2name_[tid] = name;
47 name2id_[name] = tid;
48 return;
49 }
50
Get(const std::string & name)51 std::optional<std::thread::id> ThreadTracer::Get(const std::string& name) {
52 std::lock_guard<std::mutex> lock(mtx_);
53 if (Contains(name2id_, name)) {
54 return {name2id_[name]};
55 }
56 return std::nullopt;
57 }
58
GetThreadTracer()59 ThreadTracer& GetThreadTracer() {
60 static ThreadTracer thread_tracer;
61 return thread_tracer;
62 }
63
GetName(const std::thread::id tid)64 std::string GetName(const std::thread::id tid) {
65 return GetThreadTracer().Get(tid);
66 }
67
GetId(const std::string & name)68 std::optional<std::thread::id> GetId(const std::string& name) {
69 return GetThreadTracer().Get(name);
70 }
71
Set(const std::string & name,const std::thread::id tid)72 void Set(const std::string& name, const std::thread::id tid) {
73 GetThreadTracer().Set(name, tid);
74 }
75 } // namespace thread
76 } // namespace confui
77 } // namespace cuttlefish
78