-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleThread.h
More file actions
106 lines (98 loc) · 2.21 KB
/
SimpleThread.h
File metadata and controls
106 lines (98 loc) · 2.21 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
100
101
102
103
104
105
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: SimpleThread.h
* Author: andreas
*
* Created on December 6, 2017, 7:25 AM
*/
#ifndef SIMPLETHREAD_H
#define SIMPLETHREAD_H
#include <thread>
#include <mutex>
#include <condition_variable>
//simple automatic unlocking mutex
typedef std::unique_lock<std::mutex> Synchronized;
//simple condition variable that encapsulates the monitor
//you need to ensure that the monitor life cycle fits
//to the condition life cycle
class Condition{
private:
std::mutex *mutex;
std::condition_variable cond;
bool ownsMutex=false;
public:
Condition(std::mutex &m){
mutex=&m;
}
Condition(){
mutex=new std::mutex();
ownsMutex=true;
}
~Condition(){
if (ownsMutex) delete mutex;
}
void wait(){
Synchronized l(*mutex);
cond.wait(l);
};
void wait(int millis){
Synchronized l(*mutex);
cond.wait_for(l,std::chrono::milliseconds(millis));
}
void wait(Synchronized &s){
cond.wait(s);
}
void wait(Synchronized &s,int millis){
cond.wait_for(s,std::chrono::milliseconds(millis));
}
void notify(){
Synchronized g(*mutex);
cond.notify_one();
}
void notify(Synchronized &s){
cond.notify_one();
}
void notifyAll(){
Synchronized g(*mutex);
cond.notify_all();
}
void notifyAll(Synchronized &s){
cond.notify_all();
}
};
//java like runnable interface
class Runnable{
public:
virtual void run()=0;
};
//java like thread class
class Thread{
private:
Runnable *runnable;
std::thread *mthread=NULL;
void run(){
runnable->run();
}
public:
Thread(Runnable *runnable){
this->runnable=runnable;
};
~Thread(){
if (mthread) delete mthread;
}
void start(){
if (mthread) return;
mthread=new std::thread([this]{this->run();});
}
void join(){
if (! mthread) return;
mthread->join();
delete mthread;
mthread=NULL;
};
};
#endif /* SIMPLETHREAD_H */