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