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 "osal/thread/condition_variable.h" 24 #include "osal/thread/mutex.h" 25 #include "osal/thread/scoped_lock.h" 26 #include "osal/thread/thread.h" 27 28 namespace OHOS { 29 namespace Media { 30 namespace OSAL { 31 32 class Task { 33 public: 34 explicit Task(std::string name, ThreadPriority priority = ThreadPriority::HIGH); 35 36 explicit Task(std::string name, std::function<void()> handler, ThreadPriority priority = ThreadPriority::HIGH); 37 38 virtual ~Task(); 39 40 virtual void Start(); 41 42 virtual void Stop(); 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 std::atomic<RunningState> runningState_{RunningState::PAUSED}; 65 std::function<void()> handler_ = [this] { DoTask(); }; 66 OSAL::Thread loop_; 67 OSAL::Mutex stateMutex_{}; 68 OSAL::ConditionVariable syncCond_{}; 69 }; 70 } // namespace OSAL 71 } // namespace Media 72 } // namespace OHOS 73 #endif // HISTREAMER_FOUNDATION_OSAL_TASK_H 74