BaseThread.cpp
2.13 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
#include "BaseThread.h"
#include <stdio.h>
#include <string.h>
CBaseThread::CBaseThread()
{
m_StopEvent.ResetEvent();
}
CBaseThread::~CBaseThread()
{
}
BOOL CBaseThread::InitInstance()
{
return TRUE;
}
int CBaseThread::ExitInstance()
{
return 0;
}
int CBaseThread::Run()
{
/// @todo implement me
//inherited class should implement this function to do what the thread will do.
return 0;
}
void* BaseThreadRun(void* pvParam)
{
CBaseThread* pBaseThread;
pBaseThread = (CBaseThread*) pvParam;
pBaseThread->InitInstance();
pBaseThread->Run();
return NULL;
}
BOOL CBaseThread::BeginThread()
{
/// @todo implement me
//start the thread.
int ret;
ret = pthread_create(&m_thread, NULL, BaseThreadRun, (void*) this);
if (ret == 0)
return TRUE;
else
return FALSE;
}
void CBaseThread::JoinThread()
{
/// @todo implement me
//waiting for the thread to terminate.
int res;
void* reStr;
//if the thread is not created or not available, just return
if (m_thread == 0)
{
CONSOLE_LOG("the thread is null\n");
return;
}
res = pthread_join(m_thread, &reStr);
CONSOLE_LOG("after thread %lu join, the result = %d\n", m_thread, res);
if (res != 0)
{
CONSOLE_LOG("the join error is %s\n", strerror(res));
if (res == EDEADLK)
{
CONSOLE_LOG("A deadlock was detected\n");
}
else if (res == EINVAL)
{
CONSOLE_LOG("thread is not a joinable thread\n");
}
else if (res == EINVAL)
{
CONSOLE_LOG("Another thread is already waiting to join with this thread.\n");
}
else if (res == ESRCH)
{
CONSOLE_LOG("No thread with the ID thread could be found.\n");
}
}
}
void CBaseThread::Shutdown(BOOL bWaitForShutdown)
{
m_StopEvent.SetEvent();
if (bWaitForShutdown)
{
JoinThread();
}
else if (m_thread != 0)
{
//不等待子线程结束,让子线程继续运行,将资源回收交给系统
pthread_detach(m_thread);
}
}
BOOL CBaseThread::IsStopping(DWORD nTimeOut)
{
if (m_StopEvent.Wait(nTimeOut) == CON_EVENT_GET_IT)
{
m_StopEvent.ResetEvent();
return TRUE;
}
else
{
return FALSE;
}
}