-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.cpp
More file actions
102 lines (82 loc) · 3.12 KB
/
threadpool.cpp
File metadata and controls
102 lines (82 loc) · 3.12 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
/*
* File: threadpool.cpp
* Author: georgez
*
* Created on 12 October 2014, 17:13
*/
#include <cstdlib>
#include "threadpool.h"
#include "iasServer.h"
#include "iaService.h"
#include "task_impl.h"
// the constructor just launches some amount of workers
ThreadPool::ThreadPool(iasServer* ps, size_t t = 0)
: stop(false)
{
size_t threads= t==0 ? std::max(std::thread::hardware_concurrency(),(unsigned int)4):t;
pServer_=ps;
std::cout << "ThreadPool Creation with " << threads << std::endl;
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
task* ptask;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
ptask = this->tasks.front();
this->tasks.pop();
}
// Do the task processing, method is virtual
try{
//
if(!this->pServer_->preProcess(ptask)){
std::cerr << "Threadpool: Process Task" << std::endl;
//ptask->process();
// we need to target this task to the correct service
// get the service reference
PACKETHEAD_PTR header=(ptask->getImpl())->getHeader();
auto service=pServer_->getService(header->sid);
if(service){
service->process(ptask);
}else{
std::cerr << "ERROR: Service ID NOT FOUND" << std::endl;
}
}
}catch(...){
std::cerr << "ERROR: Task Process Exception" << std::endl;
}
// On completion of task, recycle it
this->pServer_->recycleTask(ptask);
}
}
);
}
void ThreadPool::addTask(task* tp) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
// put task on queue
tasks.push(tp);
}
condition.notify_one();
}
// the destructor joins all threads
ThreadPool::~ThreadPool()
{
std::cout << "Threadpool Destruction Started" << std::endl;
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}