| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2016 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 |
| 5 #ifndef COMPONENTS_OFFLINE_PAGES_CORE_TASK_QUEUE_H_ |
| 6 #define COMPONENTS_OFFLINE_PAGES_CORE_TASK_QUEUE_H_ |
| 7 |
| 8 #include <memory> |
| 9 #include <queue> |
| 10 |
| 11 #include "base/callback.h" |
| 12 #include "base/macros.h" |
| 13 #include "base/memory/ref_counted.h" |
| 14 #include "base/memory/weak_ptr.h" |
| 15 #include "components/offline_pages/core/task.h" |
| 16 |
| 17 namespace offline_pages { |
| 18 |
| 19 // Class for coordinating |Task|s in relation to access to a specific resource. |
| 20 // As a task, we understand a set of asynchronous operations (possibly switching |
| 21 // threads) that access a set of sensitive resource(s). Because the resource |
| 22 // state is modified and individual steps of a task are asynchronous, allowing |
| 23 // certain tasks to run in parallel may lead to incorrect results. This class |
| 24 // allows for ordering of tasks in a FIFO manner, to ensure two tasks modifying |
| 25 // a resources are not run at the same time. |
| 26 // |
| 27 // Consumers of this class should create an instance of TaskQueue and implement |
| 28 // tasks that need to be run sequentially. New task will only be started when |
| 29 // the previous one calls |Task::TaskComplete|. |
| 30 class TaskQueue { |
| 31 public: |
| 32 TaskQueue(); |
| 33 ~TaskQueue(); |
| 34 |
| 35 // Adds a task to the queue. Queue takes ownership of the task. |
| 36 void AddTask(std::unique_ptr<Task> task); |
| 37 // Whether the task queue has any pending (not-running) tasks. |
| 38 bool HasPendingTasks() const; |
| 39 // Whether there is a task currently running. |
| 40 bool HasRunningTask() const; |
| 41 |
| 42 private: |
| 43 // Checks whether there are any tasks to run, as well as whether no task is |
| 44 // currently running. When both are met, it will start the next task in the |
| 45 // queue. |
| 46 void MaybeStartTask(); |
| 47 |
| 48 // Callback for informing the queue that a task was completed. |
| 49 void TaskCompleted(Task* task); |
| 50 |
| 51 // Currently running tasks. |
| 52 std::unique_ptr<Task> current_task_; |
| 53 |
| 54 // A FIFO queue of tasks that will be run using this task queue. |
| 55 std::queue<std::unique_ptr<Task>> tasks_; |
| 56 |
| 57 base::WeakPtrFactory<TaskQueue> weak_ptr_factory_; |
| 58 |
| 59 DISALLOW_COPY_AND_ASSIGN(TaskQueue); |
| 60 }; |
| 61 |
| 62 } // namespace offline_pages |
| 63 |
| 64 #endif // COMPONENTS_OFFLINE_PAGES_CORE_TASK_QUEUE_H_ |
| OLD | NEW |