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