task-queue.cc 1.56 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/libplatform/task-queue.h"
6

7
#include "include/v8-platform.h"
8
#include "src/base/logging.h"
9 10
#include "src/base/platform/platform.h"
#include "src/base/platform/time.h"
11 12

namespace v8 {
13
namespace platform {
14

15
TaskQueue::TaskQueue() : process_queue_semaphore_(0), terminated_(false) {}
16 17


18
TaskQueue::~TaskQueue() {
19
  base::MutexGuard guard(&lock_);
20 21
  DCHECK(terminated_);
  DCHECK(task_queue_.empty());
22
}
23

24
void TaskQueue::Append(std::unique_ptr<Task> task) {
25
  base::MutexGuard guard(&lock_);
26
  DCHECK(!terminated_);
27
  task_queue_.push(std::move(task));
28
  process_queue_semaphore_.Signal();
29 30
}

31
std::unique_ptr<Task> TaskQueue::GetNext() {
32 33
  for (;;) {
    {
34
      base::MutexGuard guard(&lock_);
35
      if (!task_queue_.empty()) {
36
        std::unique_ptr<Task> result = std::move(task_queue_.front());
37 38 39 40 41
        task_queue_.pop();
        return result;
      }
      if (terminated_) {
        process_queue_semaphore_.Signal();
42
        return nullptr;
43 44 45 46
      }
    }
    process_queue_semaphore_.Wait();
  }
47 48 49
}


50
void TaskQueue::Terminate() {
51
  base::MutexGuard guard(&lock_);
52
  DCHECK(!terminated_);
53 54 55 56
  terminated_ = true;
  process_queue_semaphore_.Signal();
}

57 58 59
void TaskQueue::BlockUntilQueueEmptyForTesting() {
  for (;;) {
    {
60
      base::MutexGuard guard(&lock_);
61 62 63 64 65 66
      if (task_queue_.empty()) return;
    }
    base::OS::Sleep(base::TimeDelta::FromMilliseconds(5));
  }
}

67 68
}  // namespace platform
}  // namespace v8