-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskpool.cpp
More file actions
225 lines (210 loc) · 6.03 KB
/
taskpool.cpp
File metadata and controls
225 lines (210 loc) · 6.03 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <queue>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
using namespace std;
int32_t OnEvent(std::string& event)
{
stringstream ss;
ss << this_thread::get_id();
std::string msg = "***thread id " + ss.str() + ", event come:" + event;
std::cout << msg << endl << flush;
int sum = 0;
// 注意这段代码可能会被某些默认是O2的编译脚本优化掉,要去掉优化
for (int i = 0; i < 1e3; ++i) {
sum += i;
}
return 0;
}
class TaskPool {
public:
using Task = int32_t(const std::string&);
using BoundTask = int32_t();
TaskPool();
~TaskPool();
virtual void PushTask(std::packaged_task<BoundTask>& task);
virtual void Stop();
virtual int32_t Start(int32_t threadNum);
protected:
virtual void TaskMainWorker();
bool isRunning_ = false;
std::mutex taskMutex_;
std::vector<std::thread> threads_;
std::condition_variable hasTask_;
std::condition_variable acceptNewTask_;
std::chrono::microseconds timeoutInterval_;
std::deque<std::packaged_task<BoundTask>> tasks_;
};
TaskPool::TaskPool()
{
cout << "task pool ctor\n" << flush;
}
TaskPool::~TaskPool()
{
if (isRunning_) {
Stop();
}
cout << "task pool dtor\n" << flush;
}
int32_t TaskPool::Start(int32_t threadNum)
{
if (!threads_.empty()) {
return -1;
}
isRunning_ = true;
threads_.reserve(threadNum);
for (int i = 0; i < threadNum; ++i) {
threads_.push_back(std::thread(&TaskPool::TaskMainWorker, this));
#ifdef __linux__
auto name = "thread" + std::to_string(i);
pthread_setname_np(threads_.back().native_handle(), name.c_str());
#endif
}
return 0;
}
void TaskPool::Stop()
{
{
std::unique_lock<std::mutex> lock(taskMutex_);
isRunning_ = false;
hasTask_.notify_all();
}
for (auto& t : threads_) {
t.join();
}
}
void TaskPool::PushTask(std::packaged_task<BoundTask>& task)
{
if (threads_.empty()) {
} else {
std::unique_lock<std::mutex> lock(taskMutex_);
while (tasks_.size() >= 10) {
cout << "task pool overload\n" << flush;
hasTask_.notify_all();
acceptNewTask_.wait(lock);
}
tasks_.emplace_back(std::move(task));
hasTask_.notify_one();
}
}
void TaskPool::TaskMainWorker()
{
while (isRunning_) {
std::unique_lock<std::mutex> lock(taskMutex_);
if (tasks_.empty() && isRunning_) {
hasTask_.wait(lock);
} else {
std::packaged_task<BoundTask> task = std::move(tasks_.front());
tasks_.pop_front();
stringstream ss1;
ss1 << this_thread::get_id();
std::string msg1 = "***thread id " + ss1.str() + ", pop task\n";
std::cout << msg1 << flush;
acceptNewTask_.notify_one();
lock.unlock();
stringstream ss;
ss << this_thread::get_id();
std::string msg = "***thread id " + ss.str() + ", exec task\n";
std::cout << msg << flush;
task();
}
}
}
class EventManager : public TaskPool {
public:
EventManager() { cout << "event manager ctor\n" << flush; }
~EventManager() { cout << "event manager dtor\n" << flush; }
void StopEventLoop()
{
Stop();
eventThread_.join();
}
int32_t StartEventLoop()
{
int ret = Start(10);
if (ret != 0) {
return ret;
}
eventThread_ = std::thread(&EventManager::ProcessEvent, this);
#ifdef __linux__
pthread_setname_np(eventThread_.native_handle(), "eventloop");
#endif
return 0;
}
int32_t PushEvent(const std::string& event)
{
std::unique_lock<std::mutex> lock(mutex_);
events_.emplace(event);
hasEvent_.notify_one();
return 0;
}
private:
void ProcessEvent()
{
std::unique_lock<std::mutex> lock(mutex_);
while (isRunning_) {
if (events_.empty()) {
hasEvent_.wait(lock);
} else {
auto event = events_.front();
events_.pop();
lock.unlock();
std::packaged_task<BoundTask> task(std::bind(&OnEvent, event));
// auto future = task.get_future(); // sync mode
// std::cout << "==========push event: " << event << endl << flush;
PushTask(task);
lock.lock();
// sync mode
// if (future.wait_for(std::chrono::milliseconds(1000 * 5)) == std::future_status::ready) {
// std::cout << "=========future: " << future.get() << endl << flush;
// } else {
// std::cout << "=========future: fail " << endl << flush;
// }
}
}
}
private:
std::mutex mutex_;
std::thread eventThread_;
std::condition_variable hasEvent_;
std::queue<std::string> events_;
std::unique_ptr<std::thread> eventLoop_ = nullptr;
};
EventManager* emgr = nullptr;
void Test()
{
for (int i = 0; i < 1e7; ++i) {
emgr->PushEvent(std::to_string(i));
}
}
int main()
{
cout << "******enter for start\n" << flush;
cin.get();
emgr = new EventManager();
emgr->StartEventLoop();
std::thread t1(&Test);
std::thread t2(&Test);
#ifdef __linux__
pthread_setname_np(t1.native_handle(), "test1");
pthread_setname_np(t2.native_handle(), "test2");
#endif
if (t1.joinable()) {
t1.join();
}
if (t2.joinable()) {
t2.join();
}
cout << "******run done, entor for exit\n" << flush;
cin.get();
// vector<uint8_t> vec{1, 2, 3};
// const char* p = reinterpret_cast<const char*>(vec.data());
// cout << *p;
// cout << true;
return 0;
}