Size: 2120
Comment:
|
Size: 2000
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 5: | Line 5: |
Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed. Internally, the thread pool handle has to be created first, then the tasks are inserted into this handle and executed. | Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed. |
The Thread Pool
Thread Pools are useful when you need to limit the number of threads running in your application at the same time. There is a performance overhead associated with starting a new thread, and each thread is also allocated some memory for its stack etc.
Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed.
Thread pools are often used in multi threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently.
Implementation
The Thread Pool is a client library that is linked with every component that uses it.
Header
#include <clThreadPool.hxx>
APIs
1 namespace SAFplus
2 {
3 // Definition of user task
4 typedef uint32_t (*CallbackT) (void* invocation);
5
6 class Callable
7 {
8 public:
9 CallbackT m_fn;
10 void* m_cookie;
11
12 Callable(CallbackT fn, void* cookie);
13 void run();
14
15 };
16
17 class Poolable: public Wakeable
18 {
19 public:
20 struct timespec m_startTime;
21 struct timespec m_endTime;
22 uint32_t m_executionTimeLimit;
23 Callable* m_preIdleFn;
24 Callable* m_onDeckFn;
25
26 Poolable(Callable* preIdlFn, Callable* onDeckFn);
27 virtual void wake(int amt,void* cookie=NULL);
28 };
29
30 class ThreadPool: public Poolable
31 {
32 protected:
33 void createTask();
34 void startNewTask();
35 void taskEntry();
36
37 public:
38 short m_minThread;
39 short m_maxThread;
40 short m_numIdleTasks;
41 short m_flags;
42 tMutex m_mutex;
43 ThreadCondition m_cond;
44 uint32_t m_pendingJobs;
45
46 ThreadPool(); /* Initialize pool; call createTask() */
47 void run(); /* run task */
48
49 ~ThreadPool(); /* Finalize pool */
50
51 };
52
53 }