• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 the V8 project 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 
5 #ifndef V8_LIBPLATFORM_DELAYED_TASK_QUEUE_H_
6 #define V8_LIBPLATFORM_DELAYED_TASK_QUEUE_H_
7 
8 #include <map>
9 #include <memory>
10 #include <queue>
11 
12 #include "include/libplatform/libplatform-export.h"
13 #include "src/base/macros.h"
14 #include "src/base/platform/condition-variable.h"
15 #include "src/base/platform/mutex.h"
16 
17 namespace v8 {
18 
19 class Task;
20 
21 namespace platform {
22 
23 // DelayedTaskQueue provides queueing for immediate and delayed tasks. It does
24 // not provide any guarantees about ordering of tasks, except that immediate
25 // tasks will be run in the order that they are posted.
26 class V8_PLATFORM_EXPORT DelayedTaskQueue {
27  public:
28   using TimeFunction = double (*)();
29 
30   explicit DelayedTaskQueue(TimeFunction time_function);
31   ~DelayedTaskQueue();
32 
33   DelayedTaskQueue(const DelayedTaskQueue&) = delete;
34   DelayedTaskQueue& operator=(const DelayedTaskQueue&) = delete;
35 
36   double MonotonicallyIncreasingTime();
37 
38   // Appends an immediate task to the queue. The queue takes ownership of
39   // |task|. Tasks appended via this method will be run in order. Thread-safe.
40   void Append(std::unique_ptr<Task> task);
41 
42   // Appends a delayed task to the queue. There is no ordering guarantee
43   // provided regarding delayed tasks, both with respect to other delayed tasks
44   // and non-delayed tasks that were appended using Append(). Thread-safe.
45   void AppendDelayed(std::unique_ptr<Task> task, double delay_in_seconds);
46 
47   // Returns the next task to process. Blocks if no task is available.
48   // Returns nullptr if the queue is terminated. Will return either an immediate
49   // task posted using Append() or a delayed task where the deadline has passed,
50   // according to the |time_function| provided in the constructor. Thread-safe.
51   std::unique_ptr<Task> GetNext();
52 
53   // Terminate the queue.
54   void Terminate();
55 
56  private:
57   std::unique_ptr<Task> PopTaskFromDelayedQueue(double now);
58 
59   base::ConditionVariable queues_condition_var_;
60   base::Mutex lock_;
61   std::queue<std::unique_ptr<Task>> task_queue_;
62   std::multimap<double, std::unique_ptr<Task>> delayed_task_queue_;
63   bool terminated_ = false;
64   TimeFunction time_function_;
65 };
66 
67 }  // namespace platform
68 }  // namespace v8
69 
70 #endif  // V8_LIBPLATFORM_DELAYED_TASK_QUEUE_H_
71