1 /* 2 * Copyright (C) 2020 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 #pragma once 18 19 #include <platform/api/task_runner.h> 20 21 #include <atomic> 22 #include <condition_variable> 23 #include <map> 24 #include <mutex> 25 #include <optional> 26 #include <thread> 27 28 #include <android-base/thread_annotations.h> 29 30 namespace mdns { 31 32 // Openscreen API surface that allows for posting tasks. The underlying 33 // implementation may be single or multi-threaded, and all complication should 34 // be handled by the implementation class. The implementation must guarantee: 35 // (1) Tasks shall not overlap in time/CPU. 36 // (2) Tasks shall run sequentially, e.g. posting task A then B implies 37 // that A shall run before B. 38 // (3) If task A is posted before task B, then any mutation in A happens-before 39 // B runs (even if A and B run on different threads). 40 // 41 // Adb implementation: The PostPackagedTask* APIs are thread-safe. 42 // Another thread will handle dequeuing each item and calling it on the fdevent thread. 43 // Thus, the task runner thread is the fdevent thread, and IsRunningOnTaskRunner() shall always 44 // return true if calling from within the running Task. 45 class AdbOspTaskRunner final : public openscreen::TaskRunner { 46 public: 47 using Task = openscreen::TaskRunner::Task; 48 49 // Must be called on the fdevent thread. 50 explicit AdbOspTaskRunner(); 51 ~AdbOspTaskRunner() final; 52 void PostPackagedTask(Task task) final; 53 void PostPackagedTaskWithDelay(Task task, openscreen::Clock::duration delay) final; 54 bool IsRunningOnTaskRunner() final; 55 56 // The task executor thread. 57 void TaskExecutorWorker(); 58 59 private: 60 uint64_t thread_id_; 61 std::mutex mutex_; 62 std::multimap<std::chrono::time_point<std::chrono::steady_clock>, Task> tasks_ 63 GUARDED_BY(mutex_); 64 std::atomic<bool> terminate_loop_ = false; 65 std::condition_variable cv_; 66 std::thread task_handler_; 67 }; 68 69 } // namespace mdns 70