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 38 class ThreadPool { 39 public: 40 static ThreadPool* CreateThreadPool(int32_t number); 41 static void AddTask(Task &&task); 42 static void Destroy(); 43 44 void Init(int32_t number); 45 46 void AddNewTask(Task &&task); 47 GetThreadNumber()48 int32_t GetThreadNumber() const 49 { 50 return threadNumber_; 51 } 52 53 private: 54 void ThreadRun(int32_t threadIndex); 55 void RunTask(Task &&task, int32_t index); 56 int32_t AcquireWorkIndex(); 57 ThreadExecute(void * context,int32_t threadIndex)58 static void ThreadExecute(void* context, int32_t threadIndex) 59 { 60 ((ThreadPool*)context)->ThreadRun(threadIndex); 61 } 62 ThreadPool()63 ThreadPool() 64 { 65 } 66 ~ThreadPool(); 67 68 private: 69 static constexpr int32_t threadPoolMaxTasks = 1; 70 std::vector<std::thread> workers_; 71 std::atomic<bool> stop_ = { false }; 72 73 std::vector<TaskNode> taskQueue_; 74 std::mutex queueMutex_; 75 int32_t threadNumber_ = 0; 76 }; 77 } // namespace Uscript 78 #endif 79