1/*
2 * Copyright (c) 2021-2023 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_THREAD_H
17#define HISTREAMER_FOUNDATION_OSAL_THREAD_H
18
19#include <functional>
20#include <memory> // NOLINT
21#include <pthread.h>
22#include <string>
23#include "osal/task/mutex.h"
24
25namespace OHOS {
26namespace Media {
27enum class ThreadPriority : int {
28    LOW = 9,
29    NORMAL = 16,
30    MIDDLE = 24,
31    HIGH = 32,
32    HIGHEST = 39,
33};
34
35class Thread {
36public:
37    explicit Thread(ThreadPriority priority = ThreadPriority::HIGH) noexcept;
38
39    Thread(const Thread&) = delete;
40
41    Thread& operator=(const Thread&) = delete;
42
43    Thread(Thread&& other) noexcept;
44
45    Thread& operator=(Thread&& other) noexcept;
46
47    virtual ~Thread() noexcept;
48
49    bool HasThread() const noexcept;
50
51    void SetName(const std::string& name);
52
53    bool CreateThread(const std::function<void()>& func);
54
55    bool IsRunningInSelf();
56
57private:
58    struct State {
59        virtual ~State() = default;
60        std::function<void()> func{};
61        std::string name;
62    };
63
64    void SetNameInternal();
65    static void* Run(void* arg); // NOLINT: void*
66
67    pthread_t id_{};
68    std::string name_;
69    ThreadPriority priority_;
70    std::unique_ptr<State> state_{};
71    mutable Mutex mutex_{};
72    std::atomic<bool> isExistThread_{false};
73};
74} // namespace Media
75} // namespace OHOS
76#endif // HISTREAMER_FOUNDATION_OSAL_THREAD_H
77