#pragma once
#include <thread>
+#include <type_traits>
+
#include <pthread.h>
+
#include <folly/Range.h>
namespace folly {
inline bool setThreadName(T /* id */, StringPiece /* name */) {
static_assert(
std::is_same<T, pthread_t>::value ||
- std::is_same<T, std::thread::native_handle_type>::value,
- "type must be pthread_t or std::thread::native_handle_type");
+ std::is_same<T, std::thread::id>::value ||
+ std::is_same<T, std::thread::native_handle_type>::value,
+ "type must be pthread_t, std::thread::id or "
+ "std::thread::native_handle_type");
return false;
}
}
#endif
+template <>
+inline typename std::enable_if<
+ std::is_same<pthread_t, std::thread::native_handle_type>::value,
+ bool>::type
+setThreadName(std::thread::id id, StringPiece name) {
+ static_assert(
+ sizeof(std::thread::native_handle_type) == sizeof(decltype(id)),
+ "This assumes std::thread::id is a thin wrapper around "
+ "std::thread::native_handle_type, but that doesn't appear to be true.");
+ // In most implementations, std::thread::id is a thin wrapper around
+ // std::thread::native_handle_type, which means we can do unsafe things to
+ // extract it.
+ pthread_t ptid = *reinterpret_cast<pthread_t*>(&id);
+ return setThreadName(ptid, name);
+}
+
inline bool setThreadName(StringPiece name) {
return setThreadName(pthread_self(), name);
}
*/
#include <thread>
+
#include <folly/Baton.h>
#include <folly/ScopeGuard.h>
#include <folly/ThreadName.h>
using namespace std;
using namespace folly;
-constexpr bool expectedSetOtherThreadNameResult =
+static constexpr bool expectedSetOtherThreadNameResult =
#ifdef FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
true
#else
#endif
;
-constexpr bool expectedSetSelfThreadNameResult =
+static constexpr bool expectedSetSelfThreadNameResult =
#if defined(FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME) || \
defined(FOLLY_HAS_PTHREAD_SETNAME_NP_NAME)
true
expectedSetOtherThreadNameResult,
setThreadName(th.native_handle(), "rockin-thread"));
}
+
+TEST(ThreadName, setThreadName_other_id) {
+ Baton<> let_thread_end;
+ thread th([&] {
+ let_thread_end.wait();
+ });
+ SCOPE_EXIT { th.join(); };
+ SCOPE_EXIT { let_thread_end.post(); };
+ EXPECT_EQ(
+ expectedSetOtherThreadNameResult,
+ setThreadName(th.get_id(), "rockin-thread"));
+}