-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkolthread.h
119 lines (103 loc) · 2.2 KB
/
kolthread.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
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
#ifndef KOLTHREAD_H_INCLUDED
#define KOLTHREAD_H_INCLUDED
/* Note on Windows
* <winsock2.h> is used instead of <windows.h> because
* that the <windows.h> includes the <winsock.h> if
* <winsock2.h> is not included.
*/
#ifdef WIN32
#include <winsock2.h>
#include <process.h>
#define SEM_VALUE_MAX (2147483647)
#else
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#endif /* WIN32 */
namespace kol
{
#ifdef WIN32
typedef HANDLE mutex_t;
typedef HANDLE thread_t;
typedef HANDLE sem_t;
#else
typedef pthread_mutex_t mutex_t;
typedef pthread_t thread_t;
#endif /* WIN32 */
class Mutex
{
public:
Mutex();
virtual ~Mutex();
virtual int lock();
virtual int trylock();
virtual int unlock();
protected:
mutex_t m_mutex;
};
class Semaphore
{
public:
Semaphore(unsigned int value);
virtual ~Semaphore();
int wait();
int trywait();
int post();
protected:
sem_t m_sem;
};
class ThreadController;
class Thread
{
private:
#ifdef WIN32
static unsigned int __stdcall start_routine(void *);
#else
static void* start_routine(void *);
#endif
public:
static void millisleep(unsigned long msec);
public:
Thread();
virtual ~Thread();
virtual int start();
virtual int join();
virtual int cancel();
void controller(ThreadController* pctrl);
ThreadController* controller() const;
void delthreadid(thread_t t);
thread_t delthreadid() const;
protected:
virtual int run();
protected:
ThreadController* m_controller;
thread_t m_threadid;
thread_t m_delthreadid;
};
class ThreadController
{
private:
#ifdef WIN32
static unsigned int __stdcall ctrl_routine(void *);
#else
static void* ctrl_routine(void *);
#endif
public:
ThreadController();
virtual ~ThreadController();
bool post(Thread* p);
bool done(Thread* p);
int lock();
int unlock();
int join();
int numrunning();
void delthread(Thread* p);
private:
void closeid();
private:
int m_running;
thread_t m_threadid;
Mutex m_mutex;
};
}
#endif