OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. |
| 3 * |
| 4 * Use of this source code is governed by a BSD-style license |
| 5 * that can be found in the LICENSE file in the root of the source |
| 6 * tree. An additional intellectual property rights grant can be found |
| 7 * in the file PATENTS. All contributing project authors may |
| 8 * be found in the AUTHORS file in the root of the source tree. |
| 9 */ |
| 10 |
| 11 #include "webrtc/test/single_threaded_task_queue.h" |
| 12 |
| 13 #include <memory> |
| 14 |
| 15 #include "webrtc/rtc_base/checks.h" |
| 16 |
| 17 namespace webrtc { |
| 18 namespace test { |
| 19 |
| 20 SingleThreadedTaskQueue::SingleThreadedTaskQueue(const char* name) |
| 21 : thread_(Run, this, name), |
| 22 running_(true), |
| 23 next_identifier_(0), |
| 24 event_(false, false) { |
| 25 thread_.Start(); |
| 26 } |
| 27 |
| 28 SingleThreadedTaskQueue::~SingleThreadedTaskQueue() { |
| 29 RTC_DCHECK_RUN_ON(&owner_thread_checker_); |
| 30 { |
| 31 rtc::CritScope lock(&cs_); |
| 32 running_ = false; |
| 33 } |
| 34 event_.Set(); |
| 35 thread_.Stop(); |
| 36 } |
| 37 |
| 38 SingleThreadedTaskQueue::TaskIdentifier SingleThreadedTaskQueue::PostTask( |
| 39 Task task) { |
| 40 rtc::CritScope lock(&cs_); |
| 41 TaskIdentifier identifier = next_identifier_++; |
| 42 tasks_.emplace_back(identifier, task); |
| 43 if (tasks_.size() == 1) { |
| 44 event_.Set(); |
| 45 } |
| 46 return identifier; |
| 47 } |
| 48 |
| 49 void SingleThreadedTaskQueue::SendTask(Task task) { |
| 50 rtc::Event done(true, false); |
| 51 PostTask([&task, &done]() { |
| 52 task(); |
| 53 done.Set(); |
| 54 }); |
| 55 done.Wait(rtc::Event::kForever); |
| 56 } |
| 57 |
| 58 bool SingleThreadedTaskQueue::CancelTask(TaskIdentifier task_id) { |
| 59 rtc::CritScope lock(&cs_); |
| 60 for (auto it = tasks_.cbegin(); it != tasks_.cend(); it++) { |
| 61 if (it->first == task_id) { |
| 62 tasks_.erase(it); |
| 63 return true; |
| 64 } |
| 65 } |
| 66 return false; |
| 67 } |
| 68 |
| 69 void SingleThreadedTaskQueue::Run(void* obj) { |
| 70 static_cast<SingleThreadedTaskQueue*>(obj)->RunLoop(); |
| 71 } |
| 72 |
| 73 void SingleThreadedTaskQueue::RunLoop() { |
| 74 while (true) { |
| 75 std::pair<TaskIdentifier, Task> task; |
| 76 bool empty; |
| 77 { |
| 78 rtc::CritScope lock(&cs_); |
| 79 if (!running_) { |
| 80 return; |
| 81 } |
| 82 empty = tasks_.empty(); |
| 83 if (!empty) { |
| 84 task = tasks_.front(); |
| 85 tasks_.pop_front(); |
| 86 } |
| 87 } |
| 88 |
| 89 if (empty) { |
| 90 event_.Wait(rtc::Event::kForever); |
| 91 } else { |
| 92 task.second(); |
| 93 } |
| 94 } |
| 95 } |
| 96 |
| 97 } // namespace test |
| 98 } // namespace webrtc |
OLD | NEW |