work_id_provider.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #include "base/message_loop/work_id_provider.h"
  5. #include <memory>
  6. #include "base/memory/ptr_util.h"
  7. #include "base/no_destructor.h"
  8. #include "base/threading/thread_local.h"
  9. namespace base {
  10. // static
  11. WorkIdProvider* WorkIdProvider::GetForCurrentThread() {
  12. static NoDestructor<ThreadLocalOwnedPointer<WorkIdProvider>> instance;
  13. if (!instance->Get())
  14. instance->Set(WrapUnique(new WorkIdProvider));
  15. return instance->Get();
  16. }
  17. // This function must support being invoked while other threads are suspended so
  18. // must not take any locks, including indirectly through use of heap allocation,
  19. // LOG, CHECK, or DCHECK.
  20. unsigned int WorkIdProvider::GetWorkId() {
  21. return work_id_.load(std::memory_order_acquire);
  22. }
  23. WorkIdProvider::~WorkIdProvider() = default;
  24. void WorkIdProvider::SetCurrentWorkIdForTesting(unsigned int id) {
  25. work_id_.store(id, std::memory_order_relaxed);
  26. }
  27. void WorkIdProvider::IncrementWorkIdForTesting() {
  28. IncrementWorkId();
  29. }
  30. WorkIdProvider::WorkIdProvider() : work_id_(0) {}
  31. void WorkIdProvider::IncrementWorkId() {
  32. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  33. unsigned int next_id = work_id_.load(std::memory_order_relaxed) + 1;
  34. // Reserve 0 to mean no work items have been executed.
  35. if (next_id == 0)
  36. ++next_id;
  37. // Release order ensures this state is visible to other threads prior to the
  38. // following task/event execution.
  39. work_id_.store(next_id, std::memory_order_release);
  40. }
  41. } // namespace base