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 #include "SimpleThread.h" 18 19 namespace android { 20 namespace hardware { 21 namespace camera { 22 namespace common { 23 namespace helper { 24 SimpleThread()25SimpleThread::SimpleThread() : mDone(true), mThread() {} ~SimpleThread()26SimpleThread::~SimpleThread() { 27 // Safe to call requestExitAndWait() from the destructor because requestExitAndWait() ensures 28 // that the thread is joinable before joining on it. This is different from how 29 // android::Thread worked. 30 requestExitAndWait(); 31 } 32 run()33void SimpleThread::run() { 34 requestExitAndWait(); // Exit current execution, if any. 35 36 // start thread 37 mDone.store(false, std::memory_order_release); 38 mThread = std::thread(&SimpleThread::runLoop, this); 39 } 40 requestExitAndWait()41void SimpleThread::requestExitAndWait() { 42 // Signal thread to stop 43 mDone.store(true, std::memory_order_release); 44 45 // Wait for thread to exit if needed. This should happen in no more than one iteration of 46 // threadLoop 47 if (mThread.joinable()) { 48 mThread.join(); 49 } 50 mThread = std::thread(); 51 } 52 runLoop()53void SimpleThread::runLoop() { 54 while (!exitPending()) { 55 if (!threadLoop()) { 56 break; 57 } 58 } 59 } 60 61 } // namespace helper 62 } // namespace common 63 } // namespace camera 64 } // namespace hardware 65 } // namespace android