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 private: 50 void ThreadRun(int32_t threadIndex); 51 void RunTask(Task &&task, int32_t index); 52 int32_t AcquireWorkIndex(); 53 ThreadExecute(void * context,int32_t threadIndex)54 static void ThreadExecute(void* context, int32_t threadIndex) 55 { 56 ((ThreadPool*)context)->ThreadRun(threadIndex); 57 } 58 ThreadPool()59 ThreadPool() 60 { 61 } 62 ~ThreadPool(); 63 64 private: 65 static const int32_t THREAD_POOL_MAX_TASKS = 2; 66 std::vector<std::thread> workers_; 67 std::atomic<bool> stop_ = { false }; 68 69 std::vector<TaskNode> taskQueue_; 70 std::mutex queueMutex_; 71 int32_t threadNumber_ = 0; 72 }; 73 } // namespace uscript 74 #endif 75