-
Notifications
You must be signed in to change notification settings - Fork 5
/
Thread.cpp
76 lines (68 loc) · 1.62 KB
/
Thread.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
#include "Thread.hpp"
#include "Exception.hpp"
#ifdef ___INANITY_PLATFORM_POSIX
#include <pthread.h>
#include <time.h>
#endif
BEGIN_INANITY
Thread::Thread(ptr<ThreadHandler> handler) : handler(handler)
{
BEGIN_TRY();
#if defined(___INANITY_PLATFORM_WINDOWS)
thread = CreateThread(0, 0, ThreadRoutine, this, 0, 0);
if(!thread.IsValid())
THROW_SECONDARY("CreateThread failed", Exception::SystemError());
#elif defined(___INANITY_PLATFORM_POSIX)
if(pthread_create(&thread, 0, ThreadRoutine, this))
THROW_SECONDARY("pthread_create failed", Exception::SystemError());
#else
#error Unknown platform
#endif
Reference();
END_TRY("Can't create thread");
}
#if defined(___INANITY_PLATFORM_WINDOWS)
DWORD CALLBACK Thread::ThreadRoutine(void* self)
{
((Thread*)self)->Run();
return 0;
}
#elif defined(___INANITY_PLATFORM_POSIX)
void* Thread::ThreadRoutine(void* self)
{
((Thread*)self)->Run();
return 0;
}
#else
#error Unknown platform
#endif
void Thread::Run()
{
handler->FireData(this);
Dereference();
}
void Thread::WaitEnd()
{
#if defined(___INANITY_PLATFORM_WINDOWS)
if(WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0)
#elif defined(___INANITY_PLATFORM_POSIX)
if(pthread_join(thread, 0))
#else
#error Unknown platform
#endif
THROW_SECONDARY("Can't wait for thread end", Exception::SystemError());
}
void Thread::Sleep(int milliseconds)
{
#if defined(___INANITY_PLATFORM_WINDOWS)
::Sleep(milliseconds);
#elif defined(___INANITY_PLATFORM_POSIX)
struct timespec t;
t.tv_sec = (time_t)(milliseconds / 1000);
t.tv_nsec = (long)((milliseconds % 1000) * 1000000);
nanosleep(&t, 0);
#else
#error Unknown platform
#endif
}
END_INANITY