-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhyc_thread.cpp
More file actions
121 lines (97 loc) · 2.43 KB
/
Copy pathhyc_thread.cpp
File metadata and controls
121 lines (97 loc) · 2.43 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
120
121
#include "hyc_thread.h"
#ifdef WIN32
#include "stdafx.h" // win文件包含在预编译头文件里
#else
#include <sys/prctl.h>
#endif
HycThread::HycThread(const string &strThreadName):
#ifdef WIN32
m_handle(0),
#else
m_id(0),
#endif
m_strThreadName(strThreadName)
{
}
HycThread::~HycThread()
{
}
const string& HycThread::GetThreadName()
{
return m_strThreadName;
}
void HycThread::SetThreadName(const string &strThreadName)
{
m_strThreadName = strThreadName;
}
#ifdef WIN32 // win实现方式
const DWORD MS_VC_EXCEPTION = 0x406D1388;
// https://msdn.microsoft.com/zh-cn/library/xcb2z8hs.aspx
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void HycThread::SetNameInternal(DWORD dwThreadID, const char* cThreadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = cThreadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
unsigned __stdcall HycThread::s_ThreadProc(void* self)
{
// self obj
HycThread *_self = (HycThread*)self;
// run proc
return _self->ThreadProc();
}
HANDLE HycThread::Start()
{
// 线程id
DWORD nThreadId;
// 启动线程
m_handle = (HANDLE)_beginthreadex(NULL, 0, s_ThreadProc, (HycThread *)this, 0, (unsigned int*)&nThreadId);
// 设置线程名
SetNameInternal(nThreadId, m_strThreadName.c_str());
return m_handle;
}
void HycThread::WaitThisThread()
{
::WaitForSingleObject( m_handle, INFINITE );
}
#else // linux实现方式
void * HycThread::s_ThreadProc(void* self)
{
// self obj
HycThread *_self = (HycThread*)self;
// set thread name
prctl(PR_SET_NAME, _self->m_strThreadName.c_str());
// run proc
_self->ThreadProc();
return NULL;
}
pthread_t HycThread::Start()
{
pthread_attr_t threadAttr; // “线程”属性
pthread_attr_init(&threadAttr); // 初始化“线程”属性,这里默认是分离线程
pthread_create(&m_id, &threadAttr, s_ThreadProc, this);
return m_id;
}
void HycThread::WaitThisThread()
{
pthread_join(m_id, NULL);
}
#endif