-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThread_old.h
80 lines (71 loc) · 1.85 KB
/
Thread_old.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
/**
* \file Thread_old.h
* \brief Class representing an operating system execution thread
*/
#ifdef _POSIX
#include <pthread.h>
#include <sched.h>
#elif defined(_WIN32)
#include <windows.h>
#endif
//--------------------------------------------------------------------------------------------------
class Thread
{
public:
Thread()
{
}
virtual ~Thread()
{
}
#ifdef _POSIX
void * threadStart(void * p)
{
((Thread*)p)->run();
}
#elif defined(_WIN32)
DWORD WINAPI threadStart(void * p)
{
((Thread*)p)->run();
}
#endif
// This function will halt until the passed in thread finishes its execution
static void waitFor(Thread * thread)
{
#ifdef _POSIX
pthread_join(thread->pthreadObject, NULL);
#elif defined(_WIN32)
WaitForSingleObject(thread->threadHandle, INFINITY, TRUE);
#endif
}
// This function will make the current thread attempt to give back the
// remaining time slice to the operating system
static void yield()
{
#ifdef _POSIX
sched_yield();
#elif defined(_WIN32)
SwitchToThread();
#endif
}
// this function will start the thread
void start()
{
#ifdef _POSIX
pthread_create(&pthreadObject, NULL, threadStart, NULL);
#elif defined(_WIN32)
threadHandle = CreateThread(NULL, 0, threadStart, thread, 0, &threadID);
#endif
}
// One must implement this function in order to use the thread class. When
// the start function of a thread is called, this function is executed.
virtual void run() = 0;
protected:
#ifdef _POSIX
pthread_t pthreadObject;
#elif defined(_WIN32)
DWORD threadID;
HANDLE threadHandle;
#endif
};
//--------------------------------------------------------------------------------------------------