• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 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 <compositionengine/impl/HwcAsyncWorker.h>
18 #include <processgroup/sched_policy.h>
19 #include <pthread.h>
20 #include <sched.h>
21 #include <sys/prctl.h>
22 #include <sys/resource.h>
23 #include <system/thread_defs.h>
24 
25 #include <android-base/thread_annotations.h>
26 #include <cutils/sched_policy.h>
27 
28 namespace android::compositionengine::impl {
29 
HwcAsyncWorker()30 HwcAsyncWorker::HwcAsyncWorker() {
31     mThread = std::thread(&HwcAsyncWorker::run, this);
32     pthread_setname_np(mThread.native_handle(), "HwcAsyncWorker");
33 }
34 
~HwcAsyncWorker()35 HwcAsyncWorker::~HwcAsyncWorker() {
36     {
37         std::scoped_lock lock(mMutex);
38         mDone = true;
39         mCv.notify_all();
40     }
41     if (mThread.joinable()) {
42         mThread.join();
43     }
44 }
send(std::function<bool ()> task)45 std::future<bool> HwcAsyncWorker::send(std::function<bool()> task) {
46     std::unique_lock<std::mutex> lock(mMutex);
47     android::base::ScopedLockAssertion assumeLock(mMutex);
48     mTask = std::packaged_task<bool()>([task = std::move(task)]() { return task(); });
49     mTaskRequested = true;
50     mCv.notify_one();
51     return mTask.get_future();
52 }
53 
run()54 void HwcAsyncWorker::run() {
55     set_sched_policy(0, SP_FOREGROUND);
56     struct sched_param param = {0};
57     param.sched_priority = 2;
58     sched_setscheduler(gettid(), SCHED_FIFO, &param);
59 
60     std::unique_lock<std::mutex> lock(mMutex);
61     android::base::ScopedLockAssertion assumeLock(mMutex);
62     while (!mDone) {
63         mCv.wait(lock);
64         if (mTaskRequested && mTask.valid()) {
65             mTask();
66             mTaskRequested = false;
67         }
68     }
69 }
70 
71 } // namespace android::compositionengine::impl
72