Wyatt  1.0.1
Thread.cpp
1 /*
2  thread.cpp
3 
4  Definition of a Java style thread class in C++.
5 
6  ------------------------------------------
7 
8  Copyright (c) 2013 Vic Hargrave
9 
10  Licensed under the Apache License, Version 2.0 (the "License");
11  you may not use this file except in compliance with the License.
12  You may obtain a copy of the License at
13 
14  http://www.apache.org/licenses/LICENSE-2.0
15 
16  Unless required by applicable law or agreed to in writing, software
17  distributed under the License is distributed on an "AS IS" BASIS,
18  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  See the License for the specific language governing permissions and
20  limitations under the License.
21 */
22 
23 #include "Thread.h"
24 
25 static void* runThread(void* arg)
26 {
27  return ((Thread*)arg)->run();
28 }
29 
30 Thread::Thread() : m_tid(0), m_running(0), m_detached(0)
31 {
32  m_signal = 0;
33 }
34 
35 Thread::~Thread()
36 {
37  if (m_running == 1 && m_detached == 0) {
38  pthread_detach(m_tid);
39  }
40  if (m_running == 1) {
41  pthread_cancel(m_tid);
42  }
43 }
44 
45 int Thread::start()
46 {
47  int result = pthread_create(&m_tid, NULL, runThread, this);
48  if (result == 0) {
49  m_running = 1;
50  }
51  return result;
52 }
53 
54 int Thread::join()
55 {
56  int result = -1;
57  if (m_running == 1) {
58  result = pthread_join(m_tid, NULL);
59  if (result == 0) {
60  m_detached = 0;
61  }
62  }
63  return result;
64 }
65 
66 int Thread::detach()
67 {
68  int result = -1;
69  if (m_running == 1 && m_detached == 0) {
70  result = pthread_detach(m_tid);
71  if (result == 0) {
72  m_detached = 1;
73  }
74  }
75  return result;
76 }
77 
78 void Thread::signal(int signal)
79 {
80  m_signal = signal;
81 }
82 
83 pthread_t Thread::self() {
84  return m_tid;
85 }
Definition: Thread.h:32