-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.hpp
116 lines (81 loc) · 2.45 KB
/
thread.hpp
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
//***************************************************************************
// File thread.hpp
// Date 24.07.17 - #1
// Copyright (c) 2017-2017 s710 (s710 (at) posteo (dot) de). All rights reserved.
// --------------------------------------------------------------------------
// Ark ClusterChat / Thread class
//***************************************************************************
#ifndef THREAD_HPP
#define THREAD_HPP
#include <pthread.h>
#include "def.h"
//***************************************************************************
// Class Mutex
//***************************************************************************
class Mutex
{
friend class CondVar;
public:
Mutex();
~Mutex();
void lock();
void unlock();
int isLocked() { return locked > 0; }
int getLockCount() { return locked; }
int tryLock();
private:
pthread_mutex_t mutex;
int locked;
};
//***************************************************************************
// CondVar
//***************************************************************************
class CondVar
{
public:
CondVar();
~CondVar();
void wait(Mutex& mutex);
int timedWait(Mutex& mutex, int timeout);
int timedWaitMs(Mutex& mutex, int timeoutMs);
void broadcast();
private:
pthread_cond_t cond;
};
//***************************************************************************
// Thread
//***************************************************************************
class Thread
{
public:
enum Errors
{
errAlreadyRunning = -99
};
// object
Thread();
virtual ~Thread();
// interface
virtual int start(int blockTimeout = na);
virtual int stop(CondVar* condVar = 0);
// tests
int isState(State aState) { return state == aState; }
int sameThread() { return childTid == pthread_self(); }
protected:
void setState(State aState) { state = aState; }
// functions
virtual int init() { return done; }
virtual int exit() { return done; }
virtual int run() = 0; // threads main run loop
virtual int waitForStarted(int timeout);
static void* startThread(Thread* thread);
// data
int joined;
int exitStatus;
Mutex controlMutex;
CondVar controlCondVar;
State state;
pthread_t childTid;
pthread_attr_t attr;
};
#endif // THREAD_HPP