• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 #ifndef UTILS_THREAD_EX_H
16 #define UTILS_THREAD_EX_H
17 
18 #include <pthread.h>
19 #include <string>
20 #include <mutex>
21 #include <condition_variable>
22 
23 namespace OHOS {
24 
25 enum class ThreadStatus {
26     OK,
27     WOULD_BLOCK,
28     INVALID_OPERATION,
29     UNKNOWN_ERROR,
30 };
31 
32 enum ThreadPrio {
33     THREAD_PROI_NORMAL = 0,
34     THREAD_PROI_LOW = 10,
35     THREAD_PROI_LOWEST = 19,
36 };
37 
38 constexpr int INVALID_PTHREAD_T = -1;
39 constexpr int MAX_THREAD_NAME_LEN = 15;
40 
41 class Thread {
42 public:
43     Thread();
44     virtual ~Thread();
45 
46     ThreadStatus Start(const std::string& name, int32_t priority = THREAD_PROI_NORMAL, size_t stack = 0);
47 
48     ThreadStatus NotifyExitSync();
49     virtual void NotifyExitAsync();
50 
51     virtual bool ReadyToWork();
52 
53     bool IsExitPending() const;
54     bool IsRunning() const;
55 
GetThread()56     pthread_t GetThread() const { return thread_; }
57 
58 protected:
59     virtual bool Run() = 0; // Derived class must implement Run()
60 
61 private:
62     Thread& operator=(const Thread&) = delete;
63     static int ThreadStart(void* args);
64     ThreadStatus Join(); // pthread created as detached
65 
66 private:
67     pthread_t thread_;
68     mutable std::mutex lock_;
69     std::condition_variable cvThreadExited_;
70     ThreadStatus status_;
71     volatile bool exitPending_;
72     volatile bool running_;
73 };
74 
75 } // namespace OHOS
76 
77 #endif
78 
79