2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "hwc-drm-worker"
24 #include <sys/resource.h>
25 #include <sys/signal.h>
27 #include <cutils/log.h>
31 Worker::Worker(const char *name, int priority)
32 : name_(name), priority_(priority), exit_(false), initialized_(false) {
39 pthread_kill(thread_, SIGTERM);
40 pthread_cond_destroy(&cond_);
41 pthread_mutex_destroy(&lock_);
44 int Worker::InitWorker() {
45 int ret = pthread_cond_init(&cond_, NULL);
47 ALOGE("Failed to int thread %s condition %d", name_.c_str(), ret);
51 ret = pthread_mutex_init(&lock_, NULL);
53 ALOGE("Failed to init thread %s lock %d", name_.c_str(), ret);
54 pthread_cond_destroy(&cond_);
58 ret = pthread_create(&thread_, NULL, InternalRoutine, this);
60 ALOGE("Could not create thread %s %d", name_.c_str(), ret);
61 pthread_mutex_destroy(&lock_);
62 pthread_cond_destroy(&cond_);
69 bool Worker::initialized() const {
74 return pthread_mutex_lock(&lock_);
77 int Worker::Unlock() {
78 return pthread_mutex_unlock(&lock_);
81 int Worker::SignalLocked() {
82 return SignalThreadLocked(false);
85 int Worker::ExitLocked() {
86 int signal_ret = SignalThreadLocked(true);
88 ALOGE("Failed to signal thread %s with exit %d", name_.c_str(), signal_ret);
90 int join_ret = pthread_join(thread_, NULL);
91 if (join_ret && join_ret != ESRCH)
92 ALOGE("Failed to join thread %s in exit %d", name_.c_str(), join_ret);
94 return signal_ret | join_ret;
97 int Worker::Signal() {
100 ALOGE("Failed to acquire lock in Signal() %d\n", ret);
104 int signal_ret = SignalLocked();
108 ALOGE("Failed to release lock in Signal() %d\n", ret);
117 ALOGE("Failed to acquire lock in Exit() %d\n", ret);
121 int exit_ret = ExitLocked();
125 ALOGE("Failed to release lock in Exit() %d\n", ret);
131 int Worker::WaitForSignalOrExitLocked() {
135 int ret = pthread_cond_wait(&cond_, &lock_);
144 void *Worker::InternalRoutine(void *arg) {
145 Worker *worker = (Worker *)arg;
147 setpriority(PRIO_PROCESS, 0, worker->priority_);
150 int ret = worker->Lock();
152 ALOGE("Failed to lock %s thread %d", worker->name_.c_str(), ret);
156 bool exit = worker->exit_;
158 ret = worker->Unlock();
160 ALOGE("Failed to unlock %s thread %d", worker->name_.c_str(), ret);
171 int Worker::SignalThreadLocked(bool exit) {
175 int ret = pthread_cond_signal(&cond_);
177 ALOGE("Failed to signal condition on %s thread %d", name_.c_str(), ret);