blob: 8e406bb834bdd0b5dd856034491729c6b124874d [file]
/*
* Copyright 2026 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/task_queue_drainer.h"
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "api/scoped_refptr.h"
#include "api/sequence_checker.h"
#include "api/task_queue/pending_task_safety_flag.h"
#include "api/task_queue/task_queue_base.h"
#include "rtc_base/checks.h"
#include "rtc_base/event.h"
namespace webrtc {
TaskQueueDrainer::TaskQueueDrainer(TaskQueueBase& owner)
: owner_(owner),
safety_(PendingTaskSafetyFlag::CreateAttachedToTaskQueue(/*alive=*/true,
&owner_)) {}
TaskQueueDrainer::~TaskQueueDrainer() {
RTC_DCHECK_RUN_ON(&owner_);
safety_->SetNotAlive();
// Flush remaining queues before deleting them, because some
// TaskQueueBase::Delete() implementations (such as Chromium's
// WebRtcTaskQueue) cancel queued-but-unstarted tasks rather than running
// them.
std::vector<Event> flush_events(draining_.size());
size_t index = 0;
for (auto& [raw_queue, queue] : draining_) {
Event* flush_event = &flush_events[index++];
queue->PostTask([flush_event] { flush_event->Set(); });
}
for (Event& flush_event : flush_events) {
flush_event.Wait(Event::kForever);
}
}
void TaskQueueDrainer::Retire(
std::unique_ptr<TaskQueueBase, TaskQueueDeleter> queue) {
RTC_DCHECK_RUN_ON(&owner_);
RTC_CHECK(queue != nullptr);
TaskQueueBase* raw_queue = queue.get();
auto [it, inserted] = draining_.emplace(raw_queue, std::move(queue));
RTC_CHECK(inserted);
raw_queue->PostTask(
[this, raw_queue, owner = &owner_, safety = safety_]() mutable {
owner->PostTask(SafeTask(std::move(safety), [this, raw_queue] {
RTC_DCHECK_RUN_ON(&owner_);
draining_.extract(raw_queue);
}));
});
}
} // namespace webrtc