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 #ifndef USCRIPT_THREADPOOL_H 16 #define USCRIPT_THREADPOOL_H 17 #include <atomic> 18 #include <condition_variable> 19 #include <functional> 20 #include <mutex> 21 #include <thread> 22 #include <vector> 23 24 namespace Uscript { 25 struct Task { 26 std::function<void(int)> processor; 27 int32_t workSize; 28 }; 29 struct TaskNode { 30 Task task; 31 bool available; 32 std::vector<std::atomic_bool*> subTaskFlag; 33 }; 34 35 void SetScriptProportion(float proportion); 36 float GetScriptProportion(); 37 void SetTotalProportion(float proportion); 38 float GetTotalProportion(); 39 40 class ThreadPool { 41 public: 42 static ThreadPool* CreateThreadPool(int32_t number); 43 static void AddTask(Task &&task); 44 static void Destroy(); 45 46 void Init(int32_t number); 47 48 void AddNewTask(Task &&task); 49 GetThreadNumber()50 int32_t GetThreadNumber() const 51 { 52 return threadNumber_; 53 } 54 55 private: 56 void ThreadRun(int32_t threadIndex); 57 void RunTask(Task &&task, int32_t index); 58 int32_t AcquireWorkIndex(); 59 ThreadExecute(void * context,int32_t threadIndex)60 static void ThreadExecute(void* context, int32_t threadIndex) 61 { 62 ((ThreadPool*)context)->ThreadRun(threadIndex); 63 } 64 ThreadPool()65 ThreadPool() 66 { 67 } 68 ~ThreadPool(); 69 70 private: 71 static constexpr int32_t threadPoolMaxTasks = 1; 72 std::vector<std::thread> workers_; 73 std::atomic<bool> stop_ = { false }; 74 75 std::vector<TaskNode> taskQueue_; 76 std::mutex queueMutex_; 77 int32_t threadNumber_ = 0; 78 }; 79 } // namespace Uscript 80 #endif 81