AAudioThread.h revision a4eb0d86a29be2763be5fac51727858d5095794b
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#ifndef AAUDIO_THREAD_H
18#define AAUDIO_THREAD_H
19
20#include <atomic>
21#include <pthread.h>
22
23#include <aaudio/AAudio.h>
24
25namespace aaudio {
26
27/**
28 * Abstract class similar to Java Runnable.
29 */
30class Runnable {
31public:
32    Runnable() {};
33    virtual ~Runnable() = default;
34
35    virtual void run() = 0;
36};
37
38/**
39 * Abstraction for a host dependent thread.
40 * TODO Consider using Android "Thread" class or std::thread instead.
41 */
42class AAudioThread
43{
44public:
45    AAudioThread();
46    AAudioThread(Runnable *runnable);
47    virtual ~AAudioThread() = default;
48
49    /**
50     * Start the thread running.
51     */
52    aaudio_result_t start(Runnable *runnable = nullptr);
53
54    /**
55     * Join the thread.
56     * The caller must somehow tell the thread to exit before calling join().
57     */
58    aaudio_result_t stop();
59
60    /**
61     * This will get called in the thread.
62     * Override this or pass a Runnable to start().
63     */
64    virtual void run() {};
65
66    void dispatch(); // called internally from 'C' thread wrapper
67
68private:
69    Runnable    *mRunnable;
70    bool         mHasThread;
71    pthread_t    mThread; // initialized in constructor
72
73};
74
75} /* namespace aaudio */
76
77#endif ///AAUDIO_THREAD_H
78