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 protected: 58 virtual bool Run() = 0; // Derived class must implement Run() 59 60 private: 61 Thread& operator=(const Thread&) = delete; 62 static int ThreadStart(void* args); 63 ThreadStatus Join(); // pthread created as detached 64 65 private: 66 pthread_t thread_; 67 mutable std::mutex lock_; 68 std::condition_variable cvThreadExited_; 69 ThreadStatus status_; 70 volatile bool exitPending_; 71 volatile bool running_; 72 }; 73 74 } // namespace OHOS 75 76 #endif 77 78