/
mthread.cpp
112 lines (107 loc) · 1.96 KB
/
mthread.cpp
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
#include "mthread.h"
#ifdef _WIN32
#pragma warning(disable:4312)
#endif
bool mthread::initinstance()
{
//do prepare work;
return true;
}
void mthread::mainfunction()
{
//demo function
int i = 1;
while(brun)
{
//do things
printf("%d\n",++i);
}
}
unsigned int mthread::exitinstance()
{
//do exit thing
brun = false;
return 0;
}
unsigned int mthread::run()
{
if (!initinstance())
{
exitinstance();
return 1;
}
mainfunction();
exitinstance();
return 0;
}
#ifdef _WIN32
DWORD WINAPI mthread::threadfunction(void* param)
{
mthread* t = (mthread*)param;
unsigned int uiret = t->run();
return (DWORD)uiret;
}
#else
void* mthread::threadfunction(void* param)
{
mthread* t = (mthread*)param;
unsigned int uiret = t->run();
return (void*)uiret;
}
#endif
bool mthread::start()
{
#ifdef _WIN32
DWORD dwthreadid = 0;
HANDLE hThread = NULL;
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
mthread::threadfunction, // thread function
(void*)this, // argument to thread function
0, // use default creation flags
&dwthreadid); // returns the thread identifier
if (hThread == NULL)
{
return false;
}
// CloseHandle(hThread);
tid = dwthreadid;
hdle = (void*)hThread;
#else
pthread_t t;
int nret = pthread_create(&t,NULL,&threadfunction,(void*)this);
if (nret != 0)
{
return false;
}
tid = *(unsigned long*)(&t);
#endif
return true;
}
void mthread::millisleep(unsigned int uimillisecond)
{
#ifdef _WIN32
Sleep(uimillisecond);
#else
usleep(uimillisecond * 1000);
#endif
}
mthread::~mthread()
{
#ifdef _WIN32
if(hdle != NULL)
CloseHandle((HANDLE)hdle);
#else
#endif
}
void mthread::waitend()
{
#ifdef _WIN32
if(hdle)
WaitForSingleObject((HANDLE)hdle,INFINITE);
#else
if(tid)
pthread_join((pthread_t)tid,NULL);
#endif
}