Home | History | Annotate | Download | only in native
      1 /*
      2  * Copyright (C) 2016 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 "HandlerThread.h"
     18 
     19 namespace android {
     20 
     21 HandlerThread::HandlerThread()
     22     : mShouldQuit(false) {
     23 
     24 }
     25 
     26 HandlerThread::~HandlerThread() {
     27     quit();
     28 }
     29 
     30 sp<Looper> HandlerThread::getLooper() {
     31     Mutex::Autolock autoLock(mLock);
     32     if (mLooper.get() == 0) {
     33         mLooperWait.wait(mLock);
     34     }
     35     return mLooper;
     36 }
     37 
     38 status_t HandlerThread::start(const char* name, int32_t priority, size_t stack) {
     39     return run(name, priority, stack);
     40 }
     41 
     42 void HandlerThread::quit() {
     43     if (!isRunning()) {
     44         return;
     45     }
     46     sp<Looper> looper = getLooper();
     47     mLock.lock();
     48     mShouldQuit = true;
     49     mLock.unlock();
     50     looper->wake();
     51     requestExitAndWait();
     52 }
     53 
     54 bool HandlerThread::threadLoop() {
     55     mLock.lock();
     56     mLooper = Looper::prepare(0);
     57     mLooperWait.broadcast();
     58     mLock.unlock();
     59     while (true) {
     60         do {
     61             Mutex::Autolock autoLock(mLock);
     62             if (mShouldQuit) {
     63                 return false;
     64             }
     65         } while (false);
     66         mLooper->pollOnce(-1);
     67     }
     68     return false;
     69 }
     70 
     71 
     72 };
     73