1 /**
2  * Copyright (C) 2021 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 #ifndef ANDROID_CARSERVICE_EVSCALLBACKTHREAD_H
17 #define ANDROID_CARSERVICE_EVSCALLBACKTHREAD_H
18 
19 #include <android-base/macros.h>
20 #include <android-base/thread_annotations.h>
21 
22 #include <jni.h>
23 
24 #include <queue>
25 #include <thread>
26 
27 namespace android::automotive::evs {
28 
29 /*
30  * This class defines the thread that handles callbacks from the native Extended
31  * View System service.
32  */
33 class EvsCallbackThread final {
34     using Task = std::function<void(JNIEnv*)>;
35 
36     JavaVM* mVm;
37 
38     std::atomic<bool> mRunning;
39     std::thread mThread;
40     std::mutex mLock;
41     std::condition_variable mCondition;
42     std::queue<Task> mTaskQueue GUARDED_BY(mLock);
43 
44     // Main loop to handle enqueued tasks continuously
45     void threadLoop() EXCLUDES(mLock);
46 
47     DISALLOW_COPY_AND_ASSIGN(EvsCallbackThread);
48 
49 public:
50     explicit EvsCallbackThread(JavaVM* vm);
51     virtual ~EvsCallbackThread();
52 
53     // Adds a new task to the queue
54     void enqueue(const Task& task) EXCLUDES(mLock);
55 
56     // Stops a task handler thread
57     void stop() EXCLUDES(mLock);
58 };
59 
60 }  // namespace android::automotive::evs
61 
62 #endif  // ANDROID_CARSERVICE_EVSCALLBACKTHREAD_H
63