scoped_defer_task_posting.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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_TASK_COMMON_SCOPED_DEFER_TASK_POSTING_H_
  5. #define BASE_TASK_COMMON_SCOPED_DEFER_TASK_POSTING_H_
  6. #include "base/base_export.h"
  7. #include "base/location.h"
  8. #include "base/macros.h"
  9. #include "base/sequenced_task_runner.h"
  10. namespace base {
  11. // Tracing wants to post tasks from within a trace event within PostTask, but
  12. // this can lead to a deadlock. Create a scope to ensure that we are posting
  13. // the tasks in question outside of the scope of the lock.
  14. // NOTE: This scope affects only the thread it is created on. All other threads
  15. // still can post tasks.
  16. //
  17. // TODO(altimin): It should be possible to get rid of this scope, but this
  18. // requires refactoring TimeDomain to ensure that TimeDomain never changes and
  19. // we can read current time without grabbing a lock.
  20. class BASE_EXPORT ScopedDeferTaskPosting {
  21. public:
  22. static void PostOrDefer(scoped_refptr<SequencedTaskRunner> task_runner,
  23. const Location& from_here,
  24. OnceClosure task,
  25. base::TimeDelta delay);
  26. static bool IsPresent();
  27. ScopedDeferTaskPosting();
  28. ~ScopedDeferTaskPosting();
  29. private:
  30. static ScopedDeferTaskPosting* Get();
  31. // Returns whether the |scope| was set as active, which happens only
  32. // when the scope wasn't set before.
  33. static bool Set(ScopedDeferTaskPosting* scope);
  34. void DeferTaskPosting(scoped_refptr<SequencedTaskRunner> task_runner,
  35. const Location& from_here,
  36. OnceClosure task,
  37. base::TimeDelta delay);
  38. struct DeferredTask {
  39. DeferredTask(scoped_refptr<SequencedTaskRunner> task_runner,
  40. Location from_here,
  41. OnceClosure task,
  42. base::TimeDelta delay);
  43. DeferredTask(DeferredTask&& task);
  44. ~DeferredTask();
  45. scoped_refptr<SequencedTaskRunner> task_runner;
  46. Location from_here;
  47. OnceClosure task;
  48. base::TimeDelta delay;
  49. DISALLOW_COPY_AND_ASSIGN(DeferredTask);
  50. };
  51. std::vector<DeferredTask> deferred_tasks_;
  52. // Scopes can be nested (e.g. ScheduleWork inside PostTasks can post a task
  53. // to another task runner), so we want to know whether the scope is top-level
  54. // or not.
  55. bool top_level_scope_ = false;
  56. DISALLOW_COPY_AND_ASSIGN(ScopedDeferTaskPosting);
  57. };
  58. } // namespace base
  59. #endif // BASE_TASK_COMMON_SCOPED_DEFER_TASK_POSTING_H_