1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef HARDWARE_INTERFACES_CAMERA_COMMON_SIMPLETHREAD_H_ 18 #define HARDWARE_INTERFACES_CAMERA_COMMON_SIMPLETHREAD_H_ 19 20 #include <thread> 21 22 namespace android { 23 namespace hardware { 24 namespace camera { 25 namespace common { 26 namespace helper { 27 28 // A simple looper based on std::thread. 29 class SimpleThread { 30 public: 31 SimpleThread(); 32 virtual ~SimpleThread(); 33 34 // Explicit call to start execution of the thread. No thread is created before this function 35 // is called. 36 virtual void run() final; 37 virtual void requestExitAndWait() final; 38 39 protected: 40 // Main logic of the thread. This function is called repeatedly until it returns false. 41 // Thread execution stops if this function returns false. 42 virtual bool threadLoop() = 0; 43 44 // Returns true if the thread execution should stop. Should be used by threadLoop to check if 45 // the thread has been requested to exit. exitPending()46 virtual inline bool exitPending() final { return mDone.load(std::memory_order_acquire); } 47 48 private: 49 // Wraps threadLoop in a simple while loop that allows safe exit 50 virtual void runLoop() final; 51 52 // Flag to signal end of thread execution. This flag is checked before every iteration 53 // of threadLoop. 54 std::atomic_bool mDone; 55 std::thread mThread; 56 }; 57 58 } // namespace helper 59 } // namespace common 60 } // namespace camera 61 } // namespace hardware 62 } // namespace android 63 64 #endif // HARDWARE_INTERFACES_CAMERA_COMMON_SIMPLETHREAD_H_ 65