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 "sched/execute_ctx.h" 24 namespace ffrt { 25 using TimePoint = std::chrono::steady_clock::time_point; 26 27 struct DelayedWork { 28 WaitEntry* we; 29 const std::function<void(WaitEntry*)>* cb; 30 }; 31 32 class DelayedWorker { 33 std::multimap<TimePoint, DelayedWork> map; 34 std::mutex lock; 35 std::atomic_bool toExit = false; 36 std::unique_ptr<std::thread> delayedWorker = nullptr; 37 int noTaskDelayCount_{0}; 38 bool exited_ = true; 39 int epollfd_{-1}; 40 int timerfd_{-1}; 41 #ifdef FFRT_WORKERS_DYNAMIC_SCALING 42 int monitorfd_{-1}; 43 #endif 44 std::atomic<int> asyncTaskCnt_ {0}; 45 int HandleWork(void); 46 void ThreadInit(); 47 48 public: 49 static DelayedWorker &GetInstance(); 50 static void ThreadEnvCreate(); 51 static bool IsDelayerWorkerThread(); 52 53 DelayedWorker(DelayedWorker const&) = delete; 54 void operator=(DelayedWorker const&) = delete; 55 56 bool dispatch(const TimePoint& to, WaitEntry* we, const std::function<void(WaitEntry*)>& wakeup, 57 bool skipTimeCheck = false); 58 bool remove(const TimePoint& to, WaitEntry* we); 59 void SubmitAsyncTask(std::function<void()>&& func); 60 void Terminate(); 61 62 private: 63 DelayedWorker(); 64 void DumpMap(); 65 ~DelayedWorker(); 66 }; 67 } // namespace ffrt 68 #endif 69