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