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     int HandleWork(void);
47     void ThreadInit();
48 
49 public:
50     static DelayedWorker &GetInstance();
51     static void ThreadEnvCreate();
52     static bool IsDelayerWorkerThread();
53 
54     DelayedWorker(DelayedWorker const&) = delete;
55     void operator=(DelayedWorker const&) = delete;
56 
57     bool dispatch(const TimePoint& to, WaitEntry* we, const std::function<void(WaitEntry*)>& wakeup);
58     bool remove(const TimePoint& to, WaitEntry* we);
59 
60 private:
61     DelayedWorker();
62     void DumpMap();
63     ~DelayedWorker();
64 };
65 } // namespace ffrt
66 #endif
67