1 /* 2 * Copyright (C) 2011 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 #include "osThread.h" 17 18 namespace osUtils { 19 20 Thread::Thread() : 21 m_thread((pthread_t)NULL), 22 m_exitStatus(0), 23 m_isRunning(false) 24 { 25 pthread_mutex_init(&m_lock, NULL); 26 } 27 28 Thread::~Thread() 29 { 30 pthread_mutex_destroy(&m_lock); 31 } 32 33 bool 34 Thread::start() 35 { 36 pthread_mutex_lock(&m_lock); 37 m_isRunning = true; 38 int ret = pthread_create(&m_thread, NULL, Thread::thread_main, this); 39 if(ret) { 40 m_isRunning = false; 41 } 42 pthread_mutex_unlock(&m_lock); 43 return m_isRunning; 44 } 45 46 bool 47 Thread::wait(int *exitStatus) 48 { 49 if (!m_isRunning) { 50 return false; 51 } 52 53 void *retval; 54 if (pthread_join(m_thread,&retval)) { 55 return false; 56 } 57 58 long long int ret=(long long int)retval; 59 if (exitStatus) { 60 *exitStatus = (int)ret; 61 } 62 return true; 63 } 64 65 bool 66 Thread::trywait(int *exitStatus) 67 { 68 bool ret = false; 69 70 pthread_mutex_lock(&m_lock); 71 if (!m_isRunning) { 72 *exitStatus = m_exitStatus; 73 ret = true; 74 } 75 pthread_mutex_unlock(&m_lock); 76 return ret; 77 } 78 79 void * 80 Thread::thread_main(void *p_arg) 81 { 82 Thread *self = (Thread *)p_arg; 83 int ret = self->Main(); 84 85 pthread_mutex_lock(&self->m_lock); 86 self->m_isRunning = false; 87 self->m_exitStatus = ret; 88 pthread_mutex_unlock(&self->m_lock); 89 90 return (void*)ret; 91 } 92 93 } // of namespace osUtils 94 95