1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "perfetto/ext/base/weak_runner.h"
18
19 #include "perfetto/base/task_runner.h"
20
21 namespace perfetto::base {
22
WeakRunner(base::TaskRunner * task_runner)23 WeakRunner::WeakRunner(base::TaskRunner* task_runner)
24 : task_runner_(task_runner), destroyed_(std::make_shared<bool>(false)) {}
25
~WeakRunner()26 WeakRunner::~WeakRunner() {
27 *destroyed_ = true;
28 }
29
PostTask(std::function<void ()> f) const30 void WeakRunner::PostTask(std::function<void()> f) const {
31 task_runner_->PostTask([destroyed = destroyed_, f = std::move(f)]() {
32 if (*destroyed) {
33 return;
34 }
35 f();
36 });
37 }
38
PostDelayedTask(std::function<void ()> f,uint32_t delay_ms) const39 void WeakRunner::PostDelayedTask(std::function<void()> f,
40 uint32_t delay_ms) const {
41 task_runner_->PostDelayedTask(
42 [destroyed = destroyed_, f = std::move(f)]() {
43 if (*destroyed) {
44 return;
45 }
46 f();
47 },
48 delay_ms);
49 }
50
51 } // namespace perfetto::base
52