Debian Codegraph @

src/tools/davix_thread_pool.cpp

raw
1 /*
2 * This File is part of Davix, The IO library for HTTP based protocols
3 * Copyright (C) CERN 2013
4 * Author: Kwong Tat Cheung <[email protected]>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 *
20 */
21
22 #include <tools/davix_thread_pool.hpp>
23 #include <utils/davix_logger_internal.hpp>
24
25 namespace Davix{
26
27 DavixThreadPool::DavixThreadPool(DavixTaskQueue* tq, const int pool_size) :
28 _tq(tq),
29 threadCount(0),
30 _pool_size(pool_size)
31 {
32 init();
33 }
34
35 DavixThreadPool::~DavixThreadPool(){
36 for(int i=0; i<_pool_size; ++i){
37 if(tp[i])
38 delete tp[i];
39 }
40 if(tp) delete tp;
41 }
42
43 void DavixThreadPool::init(){
44 tp = new DavixThread*[_pool_size];
45
46 if(tp){
47 for(int i=0; i<_pool_size; ++i){
48 tp[i] = NULL;
49 tp[i] = new DavixThread(_tq, i);
50 if(tp[i] != NULL){
51 tp[i]->createWorkerThread();
52 threadCount++;
53 }
54 else
55 std::cerr << std::endl << "Failed to create worker thread: " << i << std::endl;
56 }
57 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThreadPool) Threadpool initiated. Number of worker threads is: {}", threadCount);
58 }
59 else
60 std::cerr << std::endl << "Failed to init threadpool!" << std::endl;
61 }
62
63 void DavixThreadPool::shutdown(){
64 int count = 0;
65 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThreadPool) Shutting down threadpool. Number of threads to join: {}", threadCount);
66 _tq->shutdown();
67 for(int i=0; i<_pool_size; ++i){
68 if(tp[i] != NULL){
69 tp[i]->shutdown();
70 if(pthread_join(tp[i]->getWorkerHandle(), NULL) != 0){
71 std::cerr << std::endl << "Failed to join worker thread: " << i << std::endl;
72 continue;
73 }
74 count++;
75 }
76 }
77 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThreadPool) Threadpool stopped. Number of threads joined: {}/{}", count, threadCount);
78 }
79
80 int DavixThreadPool::getThreadCount(){
81 return threadCount;
82 }
83
84 bool DavixThreadPool::allThreadsIdle(){
85 for(int i = 0; i < threadCount; ++i){
86 if(tp[i]->getWorkerState() == WorkerState::BUSY)
87 return false;
88 }
89 return true;
90 }
91
92 }