• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <string>
25 #include "queue_util.h"
26 
27 #define LOG_TAG "TaskExecutor"
28 
29 namespace OHOS {
30 namespace IntellVoiceUtils {
31 class TaskExecutor : private QueueUtil<std::function<void()>> {
32 public:
33     TaskExecutor(const std::string &threadName, uint32_t capacity);
34     ~TaskExecutor();
35     void StartThread();
36     void StopThread();
37     template <typename F>
38     void AddAsyncTask(F &&func, const std::string &desc = "", bool isWait = true)
39     {
40         auto task = std::make_shared<std::packaged_task<void()>>(std::forward<F>(func));
41         if (!Push([task]() { (*task)(); }, isWait)) {
42             INTELL_VOICE_LOG_ERROR("failed to push task, desc:%{public}s, isWait:%{public}d", desc.c_str(), isWait);
43         }
44     }
45     template <typename F, typename... Args>
46     auto AddSyncTask(F &&func, Args &&...args) -> decltype(func(args...))
47     {
48         auto task = std::make_shared<std::packaged_task<decltype(func(args...))()>>(std::bind(
49             std::forward<F>(func), std::forward<Args>(args)...));
50         auto ret = task->get_future();
51         Push([task]() { (*task)(); });
52 
53         ret.wait();
54         return ret.get();
55     }
56 
57 private:
58     static void *ExecuteInThread(void *arg);
59 
60 private:
61     std::mutex mutex_;
62     std::string threadName_;
63     pthread_t tid_ = 0;
64     bool isRuning_ = false;
65 };
66 }
67 }
68 
69 #undef LOG_TAG
70 
71 #endif