1 /* 2 * Copyright (c) 2024 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 INTELL_VOICE_TASK_EXECUTOR_H 16 #define INTELL_VOICE_TASK_EXECUTOR_H 17 #include <mutex> 18 #include <thread> 19 #include <memory> 20 #include <functional> 21 #include <future> 22 #include <pthread.h> 23 #include <sys/types.h> 24 #include "queue_util.h" 25 26 namespace OHOS { 27 namespace IntellVoiceUtils { 28 class TaskExecutor : private QueueUtil<std::function<void()>> { 29 public: 30 TaskExecutor(const std::string &threadName, uint32_t capacity); 31 ~TaskExecutor(); 32 void StartThread(); 33 void StopThread(); 34 template <typename F> AddAsyncTask(F && func)35 void AddAsyncTask(F &&func) 36 { 37 auto task = std::make_shared<std::packaged_task<void()>>(std::forward<F>(func)); 38 Push([task]() { (*task)(); }); 39 } 40 template <typename F, typename... Args> 41 auto AddSyncTask(F &&func, Args &&...args) -> decltype(func(args...)) 42 { 43 auto task = std::make_shared<std::packaged_task<decltype(func(args...))()>>(std::bind( 44 std::forward<F>(func), std::forward<Args>(args)...)); 45 auto ret = task->get_future(); 46 Push([task]() { (*task)(); }); 47 48 ret.wait(); 49 return ret.get(); 50 } 51 52 private: 53 static void *ExecuteInThread(void *arg); 54 55 private: 56 std::mutex mutex_; 57 std::string threadName_; 58 pthread_t tid_ = 0; 59 bool isRuning_ = false; 60 }; 61 } 62 } 63 #endif