Support setting thread name via std::thread::id
[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 static constexpr bool expectedSetOtherThreadNameResult =
28 #ifdef FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
29     true
30 #else
31     false // This system has no known way to set the name of another thread
32 #endif
33     ;
34
35 static constexpr bool expectedSetSelfThreadNameResult =
36 #if defined(FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME) || \
37     defined(FOLLY_HAS_PTHREAD_SETNAME_NP_NAME)
38     true
39 #else
40     false // This system has no known way to set its own thread name
41 #endif
42     ;
43
44 TEST(ThreadName, setThreadName_self) {
45   thread th([] {
46     EXPECT_EQ(expectedSetSelfThreadNameResult, setThreadName("rockin-thread"));
47   });
48   SCOPE_EXIT { th.join(); };
49 }
50
51 TEST(ThreadName, setThreadName_other_pthread) {
52   Baton<> handle_set;
53   Baton<> let_thread_end;
54   pthread_t handle;
55   thread th([&] {
56       handle = pthread_self();
57       handle_set.post();
58       let_thread_end.wait();
59   });
60   SCOPE_EXIT { th.join(); };
61   handle_set.wait();
62   SCOPE_EXIT { let_thread_end.post(); };
63   EXPECT_EQ(
64       expectedSetOtherThreadNameResult, setThreadName(handle, "rockin-thread"));
65 }
66
67 TEST(ThreadName, setThreadName_other_native) {
68   Baton<> let_thread_end;
69   thread th([&] {
70       let_thread_end.wait();
71   });
72   SCOPE_EXIT { th.join(); };
73   SCOPE_EXIT { let_thread_end.post(); };
74   EXPECT_EQ(
75       expectedSetOtherThreadNameResult,
76       setThreadName(th.native_handle(), "rockin-thread"));
77 }
78
79 TEST(ThreadName, setThreadName_other_id) {
80   Baton<> let_thread_end;
81   thread th([&] {
82       let_thread_end.wait();
83   });
84   SCOPE_EXIT { th.join(); };
85   SCOPE_EXIT { let_thread_end.post(); };
86   EXPECT_EQ(
87       expectedSetOtherThreadNameResult,
88       setThreadName(th.get_id(), "rockin-thread"));
89 }