-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCThread.cpp
More file actions
119 lines (102 loc) · 1.68 KB
/
CThread.cpp
File metadata and controls
119 lines (102 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "utils/CThread.h"
CThread::CThread(bool release /* = true */)
:m_thread(0)
,m_running(true)
,m_release(false)
,m_b_delete_on_exit(false)
,m_b_destructor(false)
{
m_release = release;
}
CThread::~CThread()
{
m_b_destructor = true;
if (m_running)
{
SetRelease(true);
SetRunning(false);
#ifdef _WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
#ifdef _WIN32
//if (m_thread)
// ::CloseHandle(m_thread);
#endif
}
void CThread::onStart()
{
#ifdef _WIN32
m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId);
#else
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
if (pthread_create(&m_thread,&attr, StartThread,this) == -1)
{
//perror("Thread: create failed");
SetRunning(false);
}
#endif
}
#ifdef _WIN32
unsigned _stdcall CThread::StartThread(threadparam_t id)
#else
void * CThread::StartThread(threadparam_t id)
#endif
{
CThread *p = (CThread *)id;
while (p -> m_running && !p -> m_release)
{
#ifdef _WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
if (p -> m_running)
{
p -> Run();
}
p -> SetRunning(false); // if return
if (p -> DeleteOnExit() && !p -> IsDestructor())
{
delete p;
}
#ifdef _WIN32
_endthreadex(0);
return (unsigned)NULL;
#else
return (void *)NULL;
#endif
}
bool CThread::IsRunning()
{
return m_running;
}
void CThread::SetRunning(bool x)
{
m_running = x;
}
bool CThread::IsRelease()
{
return m_release;
}
void CThread::SetRelease(bool x)
{
m_release = x;
}
bool CThread::DeleteOnExit()
{
return m_b_delete_on_exit;
}
void CThread::SetDeleteOnExit(bool x)
{
m_b_delete_on_exit = x;
}
bool CThread::IsDestructor()
{
return m_b_destructor;
}