2 libfmail: Threaded Load handler with Thread Pool
4 Copyright (C) 2007 Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@gmail.com>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program 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
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 /* Worker Thread, has a sempahore for signaling */
24 class ThreadLoadHandler
: public Thread
, public Semaphore
{
30 ThreadLoadHandler(ProtocolHandler
* pht
) : Thread(), Semaphore(){
36 /* Set client socket */
37 void setSocket(Socket
* sock
){
49 /* Wait for a job, decrement semaphore */
59 /* Decrement the semaphore */
66 ThreadLoad::ThreadLoad(ProtocolHandler
* ph
, int tpoolSize
){
69 ThreadLoadHandler
* * tpool
;
71 /* Allocate an array for the worker threads */
72 pool
= (void * *)malloc(sizeof(ThreadLoadHandler
*) * poolSize
);
73 tpool
= (ThreadLoadHandler
* *)pool
;
75 /* Create and start worker threads, all should just wait for job */
76 for (i
= 0; i
< poolSize
; i
++){
77 tpool
[i
] = new ThreadLoadHandler(ph
);
82 ThreadLoad::~ThreadLoad(){
84 ThreadLoadHandler
* * tpool
;
86 tpool
= (ThreadLoadHandler
* *)pool
;
91 for(i
= 0; i
< poolSize
; i
++){
93 if (tpool
[i
]->isReady()){
103 for(i
= 0; i
< poolSize
; i
++){
110 /* Boss thread handling code */
111 int ThreadLoad::Dispatch(Socket
* sock
, ProtocolHandler
* ph
){
113 ThreadLoadHandler
* * tpool
;
116 tpool
= (ThreadLoadHandler
* *)pool
;
121 while (dispatched
== 0){
122 /* Check semaphore value, if 0 the thread is waiting for work */
123 //tpool[i]->getValue(&v);
125 if (tpool
[i
]->TryWait() == -1){
126 /* Handle the socket to the thread (work) */
127 //printf("Dispatching to thread %i\n", i);
128 tpool
[i
]->setSocket(sock
);
130 /* Increment twice the semaphore, this to prevent
131 * handling work to a thread already doing something but
132 * with semaphore value of 0 */
141 /* Wrap i around pool size */