job_queue.cc revision 5e3f23d412006dc4db4e659864679f29341e113f
1// Copyright 2013 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#include "chrome/browser/chromeos/drive/job_queue.h"
6
7#include "base/logging.h"
8#include "base/strings/stringprintf.h"
9
10namespace drive {
11
12JobQueue::JobQueue(size_t num_max_concurrent_jobs,
13                   size_t num_priority_levels)
14    : num_max_concurrent_jobs_(num_max_concurrent_jobs),
15      queue_(num_priority_levels) {
16}
17
18JobQueue::~JobQueue() {
19}
20
21bool JobQueue::PopForRun(int accepted_priority, JobID* id) {
22  DCHECK_LT(accepted_priority, static_cast<int>(queue_.size()));
23
24  // Too many jobs are running already.
25  if (running_.size() >= num_max_concurrent_jobs_)
26    return false;
27
28  // Looks up the queue in the order of priority upto |accepted_priority|.
29  for (int priority = 0; priority <= accepted_priority; ++priority) {
30    if (!queue_[priority].empty()) {
31      *id = queue_[priority].front();
32      queue_[priority].pop_front();
33      running_.insert(*id);
34      return true;
35    }
36  }
37  return false;
38}
39
40void JobQueue::Push(JobID id, int priority) {
41  DCHECK_LT(priority, static_cast<int>(queue_.size()));
42
43  queue_[priority].push_back(id);
44}
45
46void JobQueue::MarkFinished(JobID id) {
47  size_t num_erased = running_.erase(id);
48  DCHECK_EQ(1U, num_erased);
49}
50
51std::string JobQueue::ToString() const {
52  size_t pending = 0;
53  for (size_t i = 0; i < queue_.size(); ++i)
54    pending += queue_[i].size();
55  return base::StringPrintf("pending: %d, running: %d",
56                            static_cast<int>(pending),
57                            static_cast<int>(running_.size()));
58}
59
60size_t JobQueue::GetNumberOfJobs() const {
61  size_t count = running_.size();
62  for (size_t i = 0; i < queue_.size(); ++i)
63    count += queue_[i].size();
64  return count;
65}
66
67}  // namespace drive
68