blob: 7f94a152cf8d0cba9ffbbcf8b020adc64bb1e1cf [file] [log] [blame]
John Reck322b8ab2019-03-14 13:15:28 -07001/*
2 * Copyright (C) 2019 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 "CommonPool.h"
18
19#include <sys/resource.h>
20#include <utils/Trace.h>
21#include "renderthread/RenderThread.h"
22
23#include <array>
24
25namespace android {
26namespace uirenderer {
27
28CommonPool::CommonPool() {
29 ATRACE_CALL();
30
31 CommonPool* pool = this;
32 // Create 2 workers
33 for (int i = 0; i < THREAD_COUNT; i++) {
34 std::thread worker([pool, i] {
35 {
36 std::array<char, 20> name{"hwuiTask"};
37 snprintf(name.data(), name.size(), "hwuiTask%d", i);
38 auto self = pthread_self();
39 pthread_setname_np(self, name.data());
40 setpriority(PRIO_PROCESS, 0, PRIORITY_FOREGROUND);
41 auto startHook = renderthread::RenderThread::getOnStartHook();
42 if (startHook) {
43 startHook(name.data());
44 }
45 }
46 pool->workerLoop();
47 });
48 worker.detach();
49 }
50}
51
52void CommonPool::post(Task&& task) {
53 static CommonPool pool;
54 pool.enqueue(std::move(task));
55}
56
57void CommonPool::enqueue(Task&& task) {
58 std::unique_lock lock(mLock);
59 while (!mWorkQueue.hasSpace()) {
60 lock.unlock();
61 usleep(100);
62 lock.lock();
63 }
64 mWorkQueue.push(std::move(task));
65 if (mWaitingThreads == THREAD_COUNT || (mWaitingThreads > 0 && mWorkQueue.size() > 1)) {
66 mCondition.notify_one();
67 }
68}
69
70void CommonPool::workerLoop() {
71 std::unique_lock lock(mLock);
72 while (true) {
73 if (!mWorkQueue.hasWork()) {
74 mWaitingThreads++;
75 mCondition.wait(lock);
76 mWaitingThreads--;
77 }
78 // Need to double-check that work is still available now that we have the lock
79 // It may have already been grabbed by a different thread
80 while (mWorkQueue.hasWork()) {
81 auto work = mWorkQueue.pop();
82 lock.unlock();
83 work();
84 lock.lock();
85 }
86 }
87}
88
89} // namespace uirenderer
90} // namespace android