platform_thread.cc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2018 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. #include "base/threading/platform_thread.h"
  5. #include "base/no_destructor.h"
  6. #include "base/task/current_thread.h"
  7. #include "base/threading/thread_local_storage.h"
  8. namespace base {
  9. namespace {
  10. // Returns ThreadLocalStorage slot used to store type of the current thread.
  11. // The value is stored as an integer value converted to a pointer. 1 is added to
  12. // the integer value in order to distinguish the case when the TLS slot is not
  13. // initialized.
  14. base::ThreadLocalStorage::Slot* GetThreadTypeTlsSlot() {
  15. static base::NoDestructor<base::ThreadLocalStorage::Slot> tls_slot;
  16. return tls_slot.get();
  17. }
  18. void SaveThreadTypeToTls(ThreadType thread_type) {
  19. GetThreadTypeTlsSlot()->Set(
  20. reinterpret_cast<void*>(static_cast<uintptr_t>(thread_type) + 1));
  21. }
  22. ThreadType GetThreadTypeFromTls() {
  23. uintptr_t value = reinterpret_cast<uintptr_t>(GetThreadTypeTlsSlot()->Get());
  24. // Thread type is set to kNormal by default.
  25. if (value == 0)
  26. return ThreadType::kDefault;
  27. DCHECK_LE(value - 1, static_cast<uintptr_t>(ThreadType::kMaxValue));
  28. return static_cast<ThreadType>(value - 1);
  29. }
  30. } // namespace
  31. // static
  32. void PlatformThread::SetCurrentThreadType(ThreadType thread_type) {
  33. MessagePumpType message_pump_type = MessagePumpType::DEFAULT;
  34. if (CurrentIOThread::IsSet()) {
  35. message_pump_type = MessagePumpType::IO;
  36. }
  37. #if !BUILDFLAG(IS_NACL)
  38. else if (CurrentUIThread::IsSet()) {
  39. message_pump_type = MessagePumpType::UI;
  40. }
  41. #endif
  42. internal::SetCurrentThreadType(thread_type, message_pump_type);
  43. }
  44. // static
  45. ThreadType PlatformThread::GetCurrentThreadType() {
  46. return GetThreadTypeFromTls();
  47. }
  48. namespace internal {
  49. void SetCurrentThreadType(ThreadType thread_type,
  50. MessagePumpType pump_type_hint) {
  51. SetCurrentThreadTypeImpl(thread_type, pump_type_hint);
  52. SaveThreadTypeToTls(thread_type);
  53. }
  54. } // namespace internal
  55. } // namespace base