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 #ifndef INCLUDE_PERFETTO_EXT_BASE_WEAK_RUNNER_H_ 18 #define INCLUDE_PERFETTO_EXT_BASE_WEAK_RUNNER_H_ 19 20 #include <stdint.h> 21 22 #include <functional> 23 #include <memory> 24 25 namespace perfetto::base { 26 27 class TaskRunner; 28 29 // This is a wrapper around a `base::TaskRunner*`. It is intended to be used by 30 // classes that want to post tasks on themselves. When the object is destroyed, 31 // all posted tasks become noops. 32 // 33 // A class that embeds a WeakRunner can safely capture `this` on the posted 34 // tasks. 35 class WeakRunner { 36 public: 37 explicit WeakRunner(base::TaskRunner* task_runner); 38 ~WeakRunner(); task_runner()39 base::TaskRunner* task_runner() const { return task_runner_; } 40 41 // Schedules `f` for immediate execution. `f` will not be executed is `*this` 42 // is destroyed. 43 // 44 // Can be called from any thread, but the caller needs to make sure that 45 // `*this` is alive while `PostTask` is running: this is not obvious when 46 // multiple threads are involved. 47 void PostTask(std::function<void()> f) const; 48 49 // Schedules `f` for execution after |delay_ms|. 50 // Can be called from any thread, but the caller needs to make sure that 51 // `*this` is alive while `PostDelayedTask` is running: this is not obvious 52 // when multiple threads are involved. 53 void PostDelayedTask(std::function<void()> f, uint32_t delay_ms) const; 54 55 private: 56 base::TaskRunner* const task_runner_; 57 std::shared_ptr<bool> destroyed_; 58 }; 59 60 } // namespace perfetto::base 61 62 #endif // INCLUDE_PERFETTO_EXT_BASE_WEAK_RUNNER_H_ 63