• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2024 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 #pragma once
18 
19 #include <functional>
20 #include <future>
21 #include <optional>
22 #include <thread>
23 
24 class EventLoop {
25 public:
26     void queueWork(std::function<void()>&& job);
27     ~EventLoop();
28     int getlooptid();
29 
30 private:
31     // Front queue where items are loaded
32     std::unique_ptr<std::queue<std::function<void()>>> mEventsQueue{
33             std::make_unique<std::queue<std::function<void()>>>()};
34     // Back queue where items are processed
35     std::unique_ptr<std::queue<std::function<void()>>> mEventsProcessing{
36             std::make_unique<std::queue<std::function<void()>>>()};
37     std::condition_variable mCV;
38     std::mutex mQueueMutex{};
39     std::mutex mRunnerMutex{};
40     std::promise<int> mTidPromise{};
41     std::future<int> mTidFuture = mTidPromise.get_future();
42     std::optional<int> mTid;
43     bool mStopping = false;
44     std::unique_ptr<std::thread> mRunner = std::make_unique<std::thread>(&EventLoop::run, this);
45     void run();
46 };