1 /* 2 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development 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_SHARING_THREAD_POOL_H 17 #define OHOS_SHARING_THREAD_POOL_H 18 19 #include <atomic> 20 #include <chrono> 21 #include <functional> 22 #include <future> 23 #include <list> 24 #include <memory> 25 #include <mutex> 26 #include <queue> 27 #include <thread> 28 #include <unordered_map> 29 #include "event_base.h" 30 #include "nocopyable.h" 31 32 namespace OHOS { 33 namespace Sharing { 34 35 class TaskPool : public NoCopyable { 36 public: 37 using Task = int32_t(const SharingEvent &); 38 using BindedTask = int32_t(); 39 40 TaskPool(); 41 ~TaskPool(); 42 SetMaxTaskNum(const size_t maxSize)43 virtual inline void SetMaxTaskNum(const size_t maxSize) 44 { 45 maxTaskNum_ = maxSize; 46 } 47 GetMaxTaskNum()48 virtual inline size_t GetMaxTaskNum() const 49 { 50 return maxTaskNum_; 51 } 52 GetTaskNum()53 virtual inline size_t GetTaskNum() const 54 { 55 return tasks_.size(); 56 }; 57 58 public: 59 virtual void Stop(); 60 virtual void SetTimeoutInterval(uint32_t ms); 61 virtual void PushTask(std::packaged_task<BindedTask> &task); 62 63 virtual int32_t Start(int32_t threadsNum); 64 65 protected: 66 virtual void TaskMainWorker(); 67 virtual bool IsOverload() const; 68 69 protected: 70 bool isRunning_ = false; 71 size_t maxTaskNum_ = 0; 72 std::mutex taskMutex_; 73 std::condition_variable hasTask_; 74 std::condition_variable acceptNewTask_; 75 std::chrono::milliseconds timeoutInterval_; 76 std::vector<std::thread> threads_; 77 std::deque<std::packaged_task<BindedTask>> tasks_; 78 }; 79 80 } // namespace Sharing 81 } // namespace OHOS 82 #endif