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 AUDIO_THREAD_TASK_H
16 #define AUDIO_THREAD_TASK_H
17 
18 #include <atomic>
19 #include <thread>
20 #include <functional>
21 #include <condition_variable>
22 #include <memory>
23 #include <mutex>
24 #include "nocopyable.h"
25 namespace OHOS {
26 namespace AudioStandard {
27 class __attribute__((visibility("default"))) AudioThreadTask : public NoCopyable {
28 public:
29     explicit AudioThreadTask(const std::string &name);
30     ~AudioThreadTask();
31     void Start();
32     void Stop();
33     void StopAsync();
34     void Pause();
35     void PauseAsync();
36 
37     bool CheckThreadIsRunning() const noexcept;
38 
39     void RegisterJob(std::function<void()> &&job);
40 
41 private:
42     void doEmptyJob();
43     void RunJob();
44 
45 private:
46     enum class RunningState {
47         STARTED,
48         PAUSING,
49         PAUSED,
50         STOPPING,
51         STOPPED,
52     };
53     const std::string name_;
54     std::atomic<RunningState> state_;
55     std::mutex stateMutex_;
56     std::condition_variable cond_;
57     std::unique_ptr<std::thread> loop_;
58     std::function<void()> job_ = [this] { doEmptyJob(); };
59 };
60 } // namespace AudioStandard
61 } // namespace OHOS
62 #endif
63