• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/scoped_lock.h"
26 #include "foundation/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 StopAsync();
45 
46     virtual void Pause();
47 
48     virtual void PauseAsync();
49 
50     virtual void DoTask();
51 
52     void RegisterHandler(std::function<void()> handler);
53 
54 private:
55     enum class RunningState {
56         STARTED,
57         PAUSING,
58         PAUSED,
59         STOPPING,
60         STOPPED,
61     };
62 
63     void Run();
64 
65     const std::string name_;
66     const ThreadPriority priority_;
67     std::atomic<RunningState> runningState_{RunningState::PAUSED};
68     std::function<void()> handler_ = [this] { DoTask(); };
69     std::unique_ptr<OSAL::Thread> loop_;
70     OSAL::Mutex stateMutex_{};
71     OSAL::ConditionVariable syncCond_{};
72 };
73 } // namespace OSAL
74 } // namespace Media
75 } // namespace OHOS
76 #endif // HISTREAMER_FOUNDATION_OSAL_TASK_H
77