blob: 46e89ba47b13c64674ae65a7b3d438e81dcc4031 [file] [log] [blame]
Avichal Rakeshe1857f82022-06-08 17:47:23 -07001/*
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
19namespace android {
20namespace hardware {
21namespace camera {
22namespace common {
23namespace helper {
24
25SimpleThread::SimpleThread() : mDone(true), mThread() {}
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
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
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
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