Added signal handling to smtp, nailed many memory leaks on SearchTree, WorkerThread...
[fmail.git] / src / worker.cpp
blob3f3fed7df895b35f0ee38d3b804733daf863cabc
1 /*
2 libfmail: Thread Worker Pattern Implementation
4 Copyright (C) 2008 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.
21 #include <libfmail.h>
23 Worker::Worker() : Thread(), Lock(){
24 cJob = NULL;
25 mtx = new Lock();
26 mtx->Acquire();
29 Worker::~Worker(){
30 delete mtx;
33 int Worker::setJob(Job *job, bool autodelete){
34 cJob = job;
35 autodel = autodelete;
37 return 0;
39 int Worker::wakeup(){
40 return mtx->Release();
43 int Worker::Run(){
44 onRun = 1;
45 while (onRun){
46 mtx->Acquire();
47 if (cJob){
48 cJob->Run();
50 if (autodel)
51 delete cJob;
52 cJob = NULL;
53 Release();
55 return 0;
58 Boss::Boss(int n){
59 int i;
60 workers = (Worker**)malloc(sizeof(Worker*) * n);
61 for (i = 0; i < n; i++){
62 workers[i] = new Worker();
63 workers[i]->Start();
65 nworkers = n;
68 Boss::~Boss(){
69 int i;
70 for (i = 0; i < nworkers; i++){
71 delete workers[i];
73 free(workers);
74 workers = NULL;
77 int Boss::Dispatch(Job *jb, bool autodelete){
78 int i = 0;
79 int onRun = 1;
81 while(onRun){
82 if (workers[i]->TryAcquire() == 0){
83 workers[i]->setJob(jb, autodelete);
84 workers[i]->wakeup();
85 onRun = 0;
87 i++;
88 if (i == nworkers)
89 i = 0;
91 return 1;