Add support for getting other threads' names
[folly.git] / folly / test / ThreadNameTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 <thread>
18
19 #include <folly/Baton.h>
20 #include <folly/ScopeGuard.h>
21 #include <folly/ThreadName.h>
22 #include <folly/portability/GTest.h>
23
24 using namespace std;
25 using namespace folly;
26
27 namespace {
28
29 const bool expectedSetOtherThreadNameResult = folly::canSetOtherThreadName();
30 const bool expectedSetSelfThreadNameResult = folly::canSetCurrentThreadName();
31 constexpr StringPiece kThreadName{"rockin-thread"};
32
33 } // namespace
34
35 TEST(ThreadName, getCurrentThreadName) {
36   thread th([] {
37     EXPECT_EQ(expectedSetSelfThreadNameResult, setThreadName(kThreadName));
38     if (expectedSetSelfThreadNameResult) {
39       EXPECT_EQ(kThreadName.toString(), *getCurrentThreadName());
40     }
41   });
42   SCOPE_EXIT { th.join(); };
43 }
44
45 TEST(ThreadName, setThreadName_other_pthread) {
46   Baton<> handle_set;
47   Baton<> let_thread_end;
48   pthread_t handle;
49   thread th([&] {
50       handle = pthread_self();
51       handle_set.post();
52       let_thread_end.wait();
53   });
54   SCOPE_EXIT { th.join(); };
55   handle_set.wait();
56   SCOPE_EXIT { let_thread_end.post(); };
57   EXPECT_EQ(
58       expectedSetOtherThreadNameResult, setThreadName(handle, kThreadName));
59 }
60
61 TEST(ThreadName, setThreadName_other_id) {
62   Baton<> let_thread_end;
63   thread th([&] {
64       let_thread_end.wait();
65   });
66   SCOPE_EXIT { th.join(); };
67   SCOPE_EXIT { let_thread_end.post(); };
68   EXPECT_EQ(
69       expectedSetOtherThreadNameResult,
70       setThreadName(th.get_id(), kThreadName));
71   if (expectedSetOtherThreadNameResult) {
72     EXPECT_EQ(*getThreadName(th.get_id()), kThreadName);
73   }
74 }