1 /*
2 * Copyright (C) 2016 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 #define LOG_TAG "AAudioThread"
18 //#define LOG_NDEBUG 0
19
20 #include <system_error>
21
22 #include <utils/Log.h>
23
24 #include <aaudio/AAudio.h>
25 #include <utility/AAudioUtilities.h>
26
27 #include "AAudioThread.h"
28
29 using namespace aaudio;
30
31 std::atomic<uint32_t> AAudioThread::mNextThreadIndex{1};
32
AAudioThread(const char * prefix)33 AAudioThread::AAudioThread(const char *prefix) {
34 setup(prefix);
35 }
36
AAudioThread()37 AAudioThread::AAudioThread() {
38 setup("AAudio");
39 }
40
~AAudioThread()41 AAudioThread::~AAudioThread() {
42 ALOGE_IF(mThread.get_id() == std::this_thread::get_id(),
43 "%s() destructor running in thread", __func__);
44 ALOGE_IF(mHasThread, "%s() thread never joined", __func__);
45 }
46
setup(const char * prefix)47 void AAudioThread::setup(const char *prefix) {
48 // Name the thread with an increasing index, "prefix_#", for debugging.
49 uint32_t index = mNextThreadIndex++;
50 // Wrap the index so that we do not hit the 16 char limit
51 // and to avoid hard-to-read large numbers.
52 index = index % 100000; // arbitrary
53 snprintf(mName, sizeof(mName), "%s_%u", prefix, index);
54 }
55
dispatch()56 void AAudioThread::dispatch() {
57 if (mRunnable != nullptr) {
58 mRunnable->run();
59 } else {
60 run();
61 }
62 }
63
start(Runnable * runnable)64 aaudio_result_t AAudioThread::start(Runnable *runnable) {
65 if (mHasThread) {
66 ALOGE("start() - mHasThread already true");
67 return AAUDIO_ERROR_INVALID_STATE;
68 }
69 // mRunnable will be read by the new thread when it starts. A std::thread is created.
70 mRunnable = runnable;
71 mHasThread = true;
72 mThread = std::thread(&AAudioThread::dispatch, this);
73 return AAUDIO_OK;
74 }
75
stop()76 aaudio_result_t AAudioThread::stop() {
77 if (!mHasThread) {
78 ALOGE("stop() but no thread running");
79 return AAUDIO_ERROR_INVALID_STATE;
80 }
81
82 if (mThread.get_id() == std::this_thread::get_id()) {
83 // The thread must not be joined by itself.
84 ALOGE("%s() attempt to join() from launched thread!", __func__);
85 return AAUDIO_ERROR_INTERNAL;
86 } else if (mThread.joinable()) {
87 // Double check if the thread is joinable to avoid exception when calling join.
88 mThread.join();
89 mHasThread = false;
90 return AAUDIO_OK;
91 } else {
92 ALOGE("%s() the thread is not joinable", __func__);
93 return AAUDIO_ERROR_INTERNAL;
94 }
95 }
96