-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathThreadWorker.h
90 lines (67 loc) · 1.73 KB
/
ThreadWorker.h
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
#pragma once
/*
CThreadWorker is a simple class where a operation needs to run in a background thread
- inherit CThreadWorker
- call Start/Stop to init/un-init (stop is called in destructor)
- call RunOperationInBackThread(DWORD) to start a operation in the background thread
- override OnRunBackground(DWORD) to run your operation
*/
class CThreadWorker
{
protected:
HANDLE m_hIOCP;
HANDLE m_hThread;
static DWORD __stdcall TraceThreadProc(LPVOID pvThis)
{
return ((CThreadWorker*)pvThis)->Proc();
}
DWORD Proc()
{
ATLASSERT(m_hIOCP);
DWORD dwBytes = 0;
ULONG ulKey = 0;
OVERLAPPED* pOverlapped = NULL;
while (GetQueuedCompletionStatus(m_hIOCP, &dwBytes, &ulKey, &pOverlapped, INFINITE))
{
if (!dwBytes)
break;
OnRunBackground((DWORD)ulKey);
}
return 0;
}
void RunOperationInBackThread(DWORD dwContext)
{
//ATLASSERT(m_hIOCP);
PostQueuedCompletionStatus(m_hIOCP, 1, (ULONG_PTR)dwContext, NULL);
}
void Stop()
{
if (m_hIOCP)
{
PostQueuedCompletionStatus(m_hIOCP, 0, 0, NULL);
WaitForSingleObject(m_hThread, 5000);
CloseHandle(m_hIOCP);
CloseHandle(m_hThread);
m_hIOCP = NULL;
m_hThread = NULL;
}
}
void Start()
{
if (!m_hIOCP)
{
m_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
m_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CThreadWorker::TraceThreadProc, (LPVOID)this, 0, NULL);
}
}
CThreadWorker()
{
m_hIOCP = NULL;
m_hThread = NULL;
}
virtual ~CThreadWorker()
{
Stop();
}
virtual void OnRunBackground(DWORD dwContext) = 0;
};