-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniThread.hpp
More file actions
83 lines (75 loc) · 1.59 KB
/
MiniThread.hpp
File metadata and controls
83 lines (75 loc) · 1.59 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
#pragma once
#include <thread>
#include <functional>
#include <vector>
#include <mutex>
#include <string>
#include <algorithm>
#include "WorkerInterface.h"
class MiniThread
{
public:
MiniThread();
virtual ~MiniThread();
MiniThread(const MiniThread&) = delete;
MiniThread& operator=(const MiniThread&) = delete;
void AddWorker(SpWorker);
void DelWorker(SpWorker);
private:
void Work();
private:
bool _running;
std::mutex _threadMutex;
std::thread _thread;
std::vector<SpWorker> _workers;
};
MiniThread::MiniThread() :
_running(true),
_thread(std::thread(&MiniThread::Work, this))
{
}
MiniThread::~MiniThread()
{
_running = false;
_thread.join();
}
void MiniThread::AddWorker(SpWorker worker)
{
std::lock_guard<std::mutex> lock(_threadMutex);
_workers.emplace_back(worker);
worker->SetThreadId(_thread.get_id());
}
void MiniThread::DelWorker(SpWorker worker) {
std::lock_guard<std::mutex> lock(_threadMutex);
auto iter = std::find(_workers.begin(), _workers.end(), worker);
if (_workers.end() != iter) {
_workers.erase(iter);
}
}
void MiniThread::Work()
{
while (_running) {
std::lock_guard<std::mutex> lock(_threadMutex);
if(_workers.size() == 0){
sleep_ms(10);
}
for (auto worker : _workers) {
if (worker) {
if (!worker->Work())
{
auto iter = std::find(_workers.begin(), _workers.end(), worker);
if (_workers.end() != iter){
_workers.erase(iter);
}
break;
}
}
}
}
}
/* ---------------------- ref ptr -----------------------*/
using SpThread = std::shared_ptr<MiniThread>;
SpThread CreateSpThread()
{
return std::make_shared<MiniThread>();
}