• 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 #include "EventLoop.h"
18 
19 #include <unistd.h>
20 
21 #include <mutex>
22 
23 #include "Utility.h"
24 
queueWork(std::function<void ()> && job)25 void EventLoop::queueWork(std::function<void()>&& job) {
26     {
27         std::scoped_lock lock(mQueueMutex);
28         mEventsQueue->emplace(std::move(job));
29     }
30     mCV.notify_all();
31 }
32 
~EventLoop()33 EventLoop::~EventLoop() {
34     mStopping = true;
35     mCV.notify_all();
36     mRunner->join();
37 }
38 
run()39 void EventLoop::run() {
40     mTidPromise.set_value(gettid());
41     while (!mStopping) {
42         {
43             std::unique_lock lock(mQueueMutex);
44             mCV.wait(lock, [&] { return (!mEventsQueue->empty() || mStopping); });
45             if (mStopping) {
46                 return;
47             }
48             if (!mEventsQueue->empty()) {
49                 // Swap the front and back queue
50                 mEventsQueue.swap(mEventsProcessing);
51             }
52         }
53         // Process all queued events
54         // lock not needed here since mEventsProcessing is held by this thread uniquely
55         while (!mEventsProcessing->empty() && !mStopping) {
56             // Run the item
57             {
58                 std::scoped_lock lock{mRunnerMutex};
59                 (mEventsProcessing->front())();
60             }
61             mEventsProcessing->pop();
62         }
63     }
64 }
65 
getlooptid()66 int EventLoop::getlooptid() {
67     if (!mTid.has_value()) {
68         mTid = mTidFuture.get();
69     }
70     return *mTid;
71 }