File: FXThreadPool.cpp

package info (click to toggle)
gogglesmm 1.2.5-6
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 16,812 kB
  • sloc: cpp: 231,960; ansic: 893; xml: 222; makefile: 33
file content (339 lines) | stat: -rw-r--r-- 9,456 bytes parent folder | download | duplicates (2)
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/********************************************************************************
*                                                                               *
*                             T h r e a d   P o o l                             *
*                                                                               *
*********************************************************************************
* Copyright (C) 2006,2022 by Jeroen van der Zijp.   All Rights Reserved.        *
*********************************************************************************
* This library is free software; you can redistribute it and/or modify          *
* it under the terms of the GNU Lesser General Public License as published by   *
* the Free Software Foundation; either version 3 of the License, or             *
* (at your option) any later version.                                           *
*                                                                               *
* This library is distributed in the hope that it will be useful,               *
* but WITHOUT ANY WARRANTY; without even the implied warranty of                *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                 *
* GNU Lesser General Public License for more details.                           *
*                                                                               *
* You should have received a copy of the GNU Lesser General Public License      *
* along with this program.  If not, see <http://www.gnu.org/licenses/>          *
********************************************************************************/
#include "xincs.h"
#include "fxver.h"
#include "fxdefs.h"
#include "fxmath.h"
#include "FXException.h"
#include "FXElement.h"
#include "FXArray.h"
#include "FXPtrList.h"
#include "FXAtomic.h"
#include "FXSemaphore.h"
#include "FXCompletion.h"
#include "FXRunnable.h"
#include "FXAutoThreadStorageKey.h"
#include "FXThread.h"
#include "FXWorker.h"
#include "FXLFQueue.h"
#include "FXThreadPool.h"


/*
  Notes:
  - Process tasks from lock-free queue using multiple threads.

  - A semaphore is used to block producing thread in the case the queue is full, for
    arbitrary amounts of time ranging from 0 to forever.

  - Producer ONLY ever blocks if queue is full, i.e. no free slot in the queue for an
    additional task.

  - Multiple producers may add tasks to the queue without lock-contention, if queue is
    not full.

  - Another semaphore is used to block consuming threads.  Permanent worker threads
    block indefinitely; temporary workers, if present, block only for short amount of
    time and exit when no tasks appear within that time.

  - Instead of waiting, a thread can become an additional consumer thread, except that
    it will not block but return if the queue is empty, or count becomes zero.

  - Task groups provide a mechanism to execute tasks which belong together, and allow
    the producing thread to know when the entire group is complete.

  - To this end, a task group maintains a completion object which records the number of
    tasks started versus completed, and which sports a semaphore which can coordinate
    the worker threads with the producer thread.

  - For groups of tasks belonging together, a counter is used to record the completions
    of all the tasks started in the group.  If the producer also participates in the
    processing of of tasks, it exits as soon as the completion count reaches zero or
    the task queue becomes empty.  In either case, it may have to block for a little
    while on the completion semaphore.

  - No new tasks can be posted when about to shut down; so when queue becomes empty, it
    will stay empty.

*/

using namespace FX;

/*******************************************************************************/

namespace FX {


// Locate thread pool to which worker thread belongs
FXAutoThreadStorageKey FXThreadPool::reference;


// Create thread pool
FXThreadPool::FXThreadPool(FXuint sz):queue(sz),freeslots(sz),usedslots(0),stacksize(0),expiration(forever),maximum(FXThread::processors()),minimum(1),workers(0),running(0){
  FXTRACE((100,"FXThreadPool::FXThreadPool(%d)\n",sz));
  }


// Change task queue size, return true if success
FXbool FXThreadPool::setSize(FXuint sz){
  if((sz<8) || (sz&(sz-1))){ fxerror("FXThreadPool::setSize: bad argument: %u.\n",sz); }
  if(atomicBoolCas(&running,0,2)){
    FXuint osz=queue.getSize();
    if(setSize(sz)){
      while(osz<sz){ ++osz; freeslots.post(); }
      while(osz>sz){ --osz; freeslots.wait(); }
      running=0;
      return true;
      }
    running=0;
    }
  return false;
  }


// Change minimum number of worker threads
FXbool FXThreadPool::setMinimumThreads(FXuint n){
  if(atomicBoolCas(&running,0,2)){
    minimum=n;
    running=0;
    return true;
    }
  return false;
  }


// Change maximum number of worker threads
FXbool FXThreadPool::setMaximumThreads(FXuint n){
  if(atomicBoolCas(&running,0,2)){
    maximum=FXMAX(n,1);
    running=0;
    return true;
    }
  return false;
  }


// Change expiration time
FXbool FXThreadPool::setExpiration(FXTime ns){
  if(atomicBoolCas(&running,0,2)){
    expiration=ns;
    running=0;
    return true;
    }
  return false;
  }


// Change stack size
FXbool FXThreadPool::setStackSize(FXuval sz){
  if(atomicBoolCas(&running,0,2)){
    stacksize=sz;
    running=0;
    return true;
    }
  return false;
  }


// Return calling thread's thread pool
FXThreadPool* FXThreadPool::instance(){
  return (FXThreadPool*)reference.get();
  }


// Change calling thread's thread pool
void FXThreadPool::instance(FXThreadPool *pool){
  reference.set(pool);
  }


// Start a worker and reset semaphore
FXbool FXThreadPool::startWorker(){
  threads.increment();
  if(FXWorker::execute(this,stacksize)){
    return true;
    }
  threads.decrement();
  return false;
  }


// Start thread pool
FXuint FXThreadPool::start(FXuint count){
  FXuint result=0;
  FXTRACE((150,"FXThreadPool::start(%u)\n",count));
  if(atomicBoolCas(&running,0,2)){

    // Start number of workers
    while(result<count && startWorker()){
      result++;
      }

    // Set context reference if not set yet
    if(instance()==nullptr) instance(this);

    // Start running
    running=1;
    }
  return result;
  }


// Wait until counter becomes zero, return if no new tasks posted within timeout
void FXThreadPool::runWhile(FXCompletion& comp,FXTime timeout){
  FXRunnable* task;
  while(!comp.done() && usedslots.wait(timeout) && queue.pop(task)){
    freeslots.post();
    try{
      task->run();
      }
    catch(...){
      tasks.decrement();
      throw;
      }
    tasks.decrement();
    }
  }


// Process tasks from the queue using multiple worker threads.
// When queue becomes empty, extra workers will exit if no work arrives within
// a set amount of time; the last worker to terminate will signal the semaphore.
// Any exceptions raised during task processing will be rethrown after adjusting
// the current count of workers.
FXint FXThreadPool::run(){
  FXuint w=atomicAdd(&workers,1);
  instance(this);
  try{
    runWhile(threads,(w<minimum)?forever:expiration);
    }
  catch(...){
    instance(nullptr);
    atomicAdd(&workers,-1);
    threads.decrement();
    throw;
    }
  instance(nullptr);
  atomicAdd(&workers,-1);
  threads.decrement();
  return 0;
  }


// Try to add new task to the queue, waiting for space if necessary
FXbool FXThreadPool::execute(FXRunnable* task,FXTime blocking){
  if(__likely(running==1 && task)){
    if(tasks.count()<threads.count() || maximum<=threads.count() || startWorker()){
      if(freeslots.wait(blocking)){
        tasks.increment();
        queue.push(task);
        usedslots.post();
        return true;
        }
      }
    }
  return false;
  }


// Execute task, and wait for all completion of all tasks
FXbool FXThreadPool::executeAndWait(FXRunnable* task,FXTime blocking){
  if(execute(task,blocking)){
    runWhile(tasks,0);
    tasks.wait();
    return true;
    }
  return false;
  }


// Execute task, and wait for completion
FXbool FXThreadPool::executeAndWaitFor(FXRunnable* task,FXCompletion& comp,FXTime blocking){
  if(execute(task,blocking)){
    runWhile(comp,0);
    comp.wait();
    return true;
    }
  return false;
  }


// Wait for completion of all tasks
FXbool FXThreadPool::wait(){
  if(__likely(running)){
    runWhile(tasks,0);
    tasks.wait();
    return true;
    }
  return false;
  }


// Wait for completion
FXbool FXThreadPool::waitFor(FXCompletion& comp){
  if(__likely(running)){
    runWhile(comp,0);
    comp.wait();
    return true;
    }
  return false;
  }


// Stop thread pool
FXbool FXThreadPool::stop(){
  FXTRACE((150,"FXThreadPool::stop()\n"));
  if(atomicBoolCas(&running,1,2)){
    FXint w=threads.count();

    // Help out processing tasks while waiting
    wait();

    // Queue empty now
    FXASSERT(queue.isEmpty());

    // Force all workers to stop
    while(w){ usedslots.post(); --w; }

    // Wait till last worker is done
    threads.wait();

    // Reset usedslots semaphore to zero
    while(usedslots.trywait()){ }

    // Unset context reference if set to this context
    if(instance()==this) instance(nullptr);

    // Stop running
    running=0;
    return true;
    }
  return false;
  }


// Delete thread pool
FXThreadPool::~FXThreadPool(){
  FXTRACE((100,"FXThreadPool::~FXThreadPool()\n"));
  stop();
  }

}