1 /*
2  * Copyright (C) 2021 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 OHOS_IPC_IPC_WORK_THREAD_POOL_H
17 #define OHOS_IPC_IPC_WORK_THREAD_POOL_H
18 
19 #include <condition_variable>
20 #include <functional>
21 #include <thread>
22 #include <unordered_map>
23 #include <atomic>
24 #include <mutex>
25 #include <ipc_workthread.h>
26 #include "hilog/log.h"
27 #include "log_tags.h"
28 
29 namespace OHOS {
30 #ifdef CONFIG_IPC_SINGLE
31 namespace IPC_SINGLE {
32 #endif
33 
34 class IPCWorkThreadPool {
35 public:
36     IPCWorkThreadPool(const IPCWorkThreadPool &) = delete;
37 
38     IPCWorkThreadPool(IPCWorkThreadPool &&) = delete;
39 
40     ~IPCWorkThreadPool();
41 
42     IPCWorkThreadPool &operator = (const IPCWorkThreadPool &) = delete;
43 
44     IPCWorkThreadPool &operator = (IPCWorkThreadPool &&) = delete;
45 
46     bool SpawnThread(int policy = IPCWorkThread::SPAWN_PASSIVE, int proto = IRemoteObject::IF_PROT_DEFAULT);
47 
48     bool RemoveThread(const std::string &threadName);
49 
50     void StopAllThreads();
51 
52     explicit IPCWorkThreadPool(int maxThreadNum);
53 
54     int GetMaxThreadNum() const;
55 
56     void UpdateMaxThreadNum(int maxThreadNum);
57     int GetSocketIdleThreadNum() const;
58     int GetSocketTotalThreadNum() const;
59 
60 private:
61     static constexpr int PROTO_NUM = 2;
62     std::string MakeThreadName(int proto, int &threadIndex);
63     std::unordered_map<std::string, sptr<IPCWorkThread>> threads_;
64     std::atomic<int> threadSequence_;
65     int maxThreadNum_;
66     int idleThreadNum_;
67     int idleSocketThreadNum_;
68     std::mutex mutex_;
69     static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC_COMMON, "IPCWorkThreadPool" };
70 };
71 #ifdef CONFIG_IPC_SINGLE
72 } // namespace IPC_SINGLE
73 #endif
74 } // namespace OHOS
75 #endif // OHOS_IPC_IPC_WORK_THREAD_POOL_H
76