Debian Codegraph @

src/tools/davix_thread.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 "davix_thread.hpp"
23 #include <utils/davix_logger_internal.hpp>
24
25 namespace Davix{
26
27 DavixThread::DavixThread(DavixTaskQueue* tq, int id) :
28 threadId(id),
29 _tq(tq),
30 worker(),
31 state(WorkerState::IDLE),
32 event(WorkerEvent::WORK)
33 {
34 }
35
36 DavixThread::~DavixThread(){}
37
38 int DavixThread::createWorkerThread(){
39 if(pthread_create(&worker, NULL, startThread, (void*)this) != 0){
40 return -1;
41 }
42 return 0;
43 }
44
45 void* DavixThread::startThread(void* args){
46 DavixThread* worker = (DavixThread*)args;
47 worker->run();
48 return 0;
49 }
50
51 int DavixThread::run(){
52 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThread) Worker thread: {} started", threadId);
53
54 while(true){
55 switch(event){
56 case WorkerEvent::WORK:
57 {
58 DavixOp* op = NULL;
59 op = _tq->popOp();
60
61 if(op != NULL){
62 state = WorkerState::BUSY;
63
64 int ret = op->executeOp();
65 if(ret < 0){
66 if(op->getOpType() == "DELETE")
67 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThread) Worker thread: {} failed to execute op on {}.",
68 threadId, op->getDestinationUrl());
69 else
70 DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixThread) Worker thread: {} failed to execute op on {}.",
71 threadId, op->getTargetUrl());
72
73 }
74
75 delete op;
76 state = WorkerState::IDLE;
77 }
78 break;
79 }
80 case WorkerEvent::STOP:
81 {
82 return 0;
83 break;
84 }
85 }
86
87 // if task queue is not running, nothing to do, exit
88 if(_tq->isStopped())
89 return 0;
90 }
91 return 0;
92 }
93
94 pthread_t& DavixThread::getWorkerHandle(){
95 return worker;
96 }
97
98 int DavixThread::getThreadId(){
99 return threadId;
100 }
101
102 void DavixThread::shutdown(){
103 state = WorkerState::STOPPING;
104 event = WorkerEvent::STOP;
105 }
106
107 WorkerState::WorkerState DavixThread::getWorkerState(){
108 return state;
109 }
110
111 } // namespace Davix