-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreading.cpp
More file actions
99 lines (83 loc) · 2.18 KB
/
threading.cpp
File metadata and controls
99 lines (83 loc) · 2.18 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
#include "threading.h"
Thread::Thread(Runnable* run):
runnable(run)
{
if(!runnable.get())
{
printError("Pointer creation failed");
}
threadHandle = (HANDLE)_beginthreadex(NULL, 0, Thread::startThreadRunnable,(LPVOID)this, CREATE_SUSPENDED | THREAD_SUSPEND_RESUME, &threadId);
if(!threadHandle)
{
printError("Thread creation failed");
}
}
Thread::Thread()
{
threadHandle = (HANDLE)_beginthreadex(NULL, 0, Thread::startThread,(LPVOID)this, CREATE_SUSPENDED, &threadId);
if(!threadHandle)
{
printError("Thread creation failed");
}
}
unsigned WINAPI Thread::startThreadRunnable(LPVOID pVoid)
{
Thread* runnableThread = static_cast<Thread*>(pVoid);
runnableThread->result = runnableThread->runnable->run();
runnableThread->setCompleted();
return reinterpret_cast<unsigned>(runnableThread->result);
}
unsigned WINAPI Thread::startThread(LPVOID pVoid)
{
Thread* suspendedThread = static_cast<Thread*>(pVoid);
suspendedThread->result = suspendedThread->run();
suspendedThread->setCompleted();
return reinterpret_cast<unsigned>(suspendedThread->result);
}
Thread::~Thread()
{
if(threadId != GetCurrentThreadId())
{
WaitForSingleObject(threadHandle, INFINITE);
DWORD closeResult = CloseHandle(threadHandle);
if(!closeResult)
{
printError("Thread handle close failed");
}
}
}
void Thread::start()
{
assert(threadHandle);
ResumeThread(threadHandle);
}
void* Thread::join()
{
return result;
}
void* Thread::run(){return 0;}
void Thread::terminate()
{
TerminateThread(threadHandle, NULL);
}
void Thread::setCompleted()
{
}
void Thread::suspend()
{
SuspendThread(threadHandle);
}
void Thread::printError(const QString& message)
{
TCHAR szBuf[256];
LPSTR lpErrorBuf;
DWORD errorCode = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER || FORMAT_MESSAGE_FROM_SYSTEM,
NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpErrorBuf, 0, NULL);
QErrorMessage msg;
msg.showMessage(lpErrorBuf);
LocalFree(lpErrorBuf);
exit(errorCode);
}
Runnable::~Runnable(){}