work_id_provider.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 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. #ifndef BASE_MESSAGE_LOOP_WORK_ID_PROVIDER_H_
  5. #define BASE_MESSAGE_LOOP_WORK_ID_PROVIDER_H_
  6. #include <atomic>
  7. #include "base/base_export.h"
  8. #include "base/threading/thread_checker.h"
  9. namespace base {
  10. namespace sequence_manager {
  11. namespace internal {
  12. class ThreadControllerWithMessagePumpImpl;
  13. }
  14. } // namespace sequence_manager
  15. // WorkIdProvider associates with the current thread (via TLS) an id state
  16. // reflecting the current work item being executed by the message loop. The item
  17. // is accessed lock-free from other threads to provide a snapshot of the
  18. // currently-executing work item.
  19. //
  20. // The expected user is the ThreadProfiler which samples the id along with the
  21. // thread's stack to identify cases where the same task spans multiple
  22. // samples. The state is stored in TLS rather than on the MessageLoop or the
  23. // ThreadProfiler because the lifetime relationship between the two classes
  24. // varies depending on which thread is being profiled, plus the fact that
  25. // MessageLoop doesn't have a well-defined creation point/owner on some threads.
  26. class BASE_EXPORT WorkIdProvider {
  27. public:
  28. // Returns the WorkIdProvider for the current thread. Allocates a
  29. // WorkIdProvider in TLS if not already present.
  30. static WorkIdProvider* GetForCurrentThread();
  31. // Returns the work id for the thread to which this WorkIdProvider
  32. // belongs. The work id is 0 before calls to IncrementWorkId() and always
  33. // non-zero after that point. The implementation supports being invoked while
  34. // other threads are suspended, and thus is guaranteed to take no locks,
  35. // directly or indirectly. May be called from any thread, as long as the
  36. // owning thread hasn't been destroyed.
  37. unsigned int GetWorkId();
  38. // Public to support unique_ptr<WorkIdProvider>.
  39. ~WorkIdProvider();
  40. void SetCurrentWorkIdForTesting(unsigned int id);
  41. void IncrementWorkIdForTesting();
  42. WorkIdProvider(const WorkIdProvider&) = delete;
  43. WorkIdProvider& operator=(const WorkIdProvider&) = delete;
  44. private:
  45. // Friended to allow use of IncrementWorkId().
  46. friend class sequence_manager::internal::ThreadControllerWithMessagePumpImpl;
  47. WorkIdProvider();
  48. void IncrementWorkId();
  49. std::atomic_uint work_id_;
  50. THREAD_CHECKER(thread_checker_);
  51. };
  52. } // namespace base
  53. #endif // BASE_MESSAGE_LOOP_WORK_ID_PROVIDER_H_