1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef _DELAYED_WORKER_H_ 17 #define _DELAYED_WORKER_H_ 18 19 #include <map> 20 #include <functional> 21 #include <thread> 22 #include "cpp/sleep.h" 23 #include "eu/cpu_monitor.h" 24 #include "sched/execute_ctx.h" 25 namespace ffrt { 26 using TimePoint = std::chrono::steady_clock::time_point; 27 28 struct DelayedWork { 29 WaitEntry* we; 30 const std::function<void(WaitEntry*)>* cb; 31 }; 32 33 class DelayedWorker { 34 std::multimap<TimePoint, DelayedWork> map; 35 std::mutex lock; 36 std::atomic_bool toExit = false; 37 std::unique_ptr<std::thread> delayWorker = nullptr; 38 int noTaskDelayCount_{0}; 39 bool exited_ = true; 40 int epollfd_{-1}; 41 int timerfd_{-1}; 42 #ifdef FFRT_WORKERS_DYNAMIC_SCALING 43 int monitorfd_{-1}; 44 CPUMonitor* monitor = nullptr; 45 #endif 46 std::atomic<int> asyncTaskCnt_ {0}; 47 int HandleWork(void); 48 void ThreadInit(); 49 50 public: 51 static DelayedWorker &GetInstance(); 52 static void ThreadEnvCreate(); 53 static bool IsDelayerWorkerThread(); 54 55 DelayedWorker(DelayedWorker const&) = delete; 56 void operator=(DelayedWorker const&) = delete; 57 58 bool dispatch(const TimePoint& to, WaitEntry* we, const std::function<void(WaitEntry*)>& wakeup); 59 bool remove(const TimePoint& to, WaitEntry* we); 60 void SubmitAsyncTask(std::function<void()>&& func); 61 62 private: 63 DelayedWorker(); 64 void DumpMap(); 65 ~DelayedWorker(); 66 }; 67 } // namespace ffrt 68 #endif 69