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