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