1 /* 2 * Copyright (c) 2021-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 16 #ifndef HISTREAMER_FOUNDATION_OSAL_TASK_H 17 #define HISTREAMER_FOUNDATION_OSAL_TASK_H 18 19 #include <atomic> 20 #include <functional> 21 #include <string> 22 23 #include "foundation/osal/thread/condition_variable.h" 24 #include "foundation/osal/thread/mutex.h" 25 #include "foundation/osal/thread/thread.h" 26 27 namespace OHOS { 28 namespace Media { 29 namespace OSAL { 30 class Task { 31 public: 32 explicit Task(std::string name, ThreadPriority priority = ThreadPriority::HIGH); 33 34 explicit Task(std::string name, std::function<void()> handler, ThreadPriority priority = ThreadPriority::HIGH); 35 36 virtual ~Task(); 37 38 virtual void Start(); 39 40 virtual void Stop(); 41 42 virtual void StopAsync(); 43 44 virtual void Pause(); 45 46 virtual void PauseAsync(); 47 48 virtual void DoTask(); 49 50 void RegisterHandler(std::function<void()> handler); 51 52 private: 53 enum class RunningState { 54 STARTED, 55 PAUSING, 56 PAUSED, 57 STOPPING, 58 STOPPED, 59 }; 60 61 void Run(); 62 63 const std::string name_; 64 const ThreadPriority priority_; 65 std::atomic<RunningState> runningState_{RunningState::PAUSED}; 66 std::function<void()> handler_ = [this] { DoTask(); }; 67 std::unique_ptr<OSAL::Thread> loop_; 68 OSAL::Mutex stateMutex_{}; 69 OSAL::ConditionVariable syncCond_{}; 70 }; 71 } // namespace OSAL 72 } // namespace Media 73 } // namespace OHOS 74 #endif // HISTREAMER_FOUNDATION_OSAL_TASK_H 75