-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActiveObject.hpp
More file actions
60 lines (51 loc) · 1.29 KB
/
ActiveObject.hpp
File metadata and controls
60 lines (51 loc) · 1.29 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
#ifndef ACTIVE_OBJECT_HPP
#define ACTIVE_OBJECT_HPP
#pragma once
#include "TsQueue.hpp"
#include <condition_variable>
#include <iostream>
#include <thread>
template <typename T> class ActiveObject {
private:
TsQueue<T> safeQueue;
std::condition_variable cv;
std::mutex protector;
std::thread processor;
bool shutdown;
public:
ActiveObject() : shutdown(false) {
processor = std::thread(&ActiveObject<T>::dataLoop, this);
}
virtual ~ActiveObject() {
std::cout << "ActiveObject destruct" << std::endl;
shutdown = true;
cv.notify_one();
processor.join();
}
void process(T &obj) {
safeQueue.push(obj);
std::cout << "Number of the data in the loop is" << safeQueue.size()
<< std::endl;
cv.notify_one();
}
protected:
void dataLoop() {
std::unique_lock<std::mutex> lock(protector);
while (!shutdown) {
if (safeQueue.empty()) {
std::cout << "Waiting for data..." << std::endl;
cv.wait(lock);
}
if (!shutdown) {
auto data = safeQueue.front();
run(data);
}
}
}
virtual void run(T &obj) {}
private:
ActiveObject(const ActiveObject &) = delete;
ActiveObject(const ActiveObject &&) = delete;
ActiveObject &operator=(const ActiveObject &) = delete;
};
#endif // ACTIVE_OBJECT_HPP