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
Thread()20 Thread::Thread() :
21 m_thread(NULL),
22 m_threadId(0),
23 m_isRunning(false)
24 {
25 }
26
~Thread()27 Thread::~Thread()
28 {
29 if(m_thread) {
30 CloseHandle(m_thread);
31 }
32 }
33
34 bool
start()35 Thread::start()
36 {
37 m_isRunning = true;
38 m_thread = CreateThread(NULL, 0, &Thread::thread_main, this, 0, &m_threadId);
39 if(!m_thread) {
40 m_isRunning = false;
41 }
42 return m_isRunning;
43 }
44
45 bool
wait(int * exitStatus)46 Thread::wait(int *exitStatus)
47 {
48 if (!m_isRunning) {
49 return false;
50 }
51
52 if(WaitForSingleObject(m_thread, INFINITE) == WAIT_FAILED) {
53 return false;
54 }
55
56 DWORD retval;
57 if (!GetExitCodeThread(m_thread,&retval)) {
58 return false;
59 }
60
61 m_isRunning = 0;
62
63 if (exitStatus) {
64 *exitStatus = retval;
65 }
66 return true;
67 }
68
69 bool
trywait(int * exitStatus)70 Thread::trywait(int *exitStatus)
71 {
72 if (!m_isRunning) {
73 return false;
74 }
75
76 if(WaitForSingleObject(m_thread, 0) == WAIT_OBJECT_0) {
77
78 DWORD retval;
79 if (!GetExitCodeThread(m_thread,&retval)) {
80 return true;
81 }
82
83 if (exitStatus) {
84 *exitStatus = retval;
85 }
86 return true;
87 }
88
89 return false;
90 }
91
92 DWORD WINAPI
thread_main(void * p_arg)93 Thread::thread_main(void *p_arg)
94 {
95 Thread *self = (Thread *)p_arg;
96 int ret = self->Main();
97 self->m_isRunning = false;
98 return ret;
99 }
100
101 } // of namespace osUtils
102