CLAM-Development  1.4.0
ThreadPool.cxx
Go to the documentation of this file.
1 #include "ThreadPool.hxx"
2 #include "Thread.hxx"
3 #include "PooledThread.hxx"
4 #include <algorithm>
5 
6 namespace CLAM
7 {
8 
9 ThreadPool::ThreadPool(int argInitialNumberOfThreads, bool argIsRealtime)
10  : mIsRealtime(argIsRealtime)
11 {
12  for (int counter = 0; counter < argInitialNumberOfThreads; counter++)
13  {
14  idleThreads.push_back( new CLAM::PooledThread(this, mIsRealtime) );
15  }
16 }
18 {
19  EmptyPool();
20 }
21 
23 {
24  Mutex::ScopedLock lock( dequeMutex );
25 
26  // First we stop and delete all the busy threads
27  for (int counter = 0; counter < busyThreads.size(); counter++)
28  {
29  PooledThread* threadPtr = busyThreads.at( counter );
30  if (threadPtr != NULL)
31  {
32  if (threadPtr->IsRunning())
33  threadPtr->Stop();
34  delete threadPtr;
35  }
36  }
37  busyThreads.clear();
38 
39  // Next we delete all the idle threads
40  for (int counter = 0; counter < idleThreads.size(); counter++)
41  {
42 
43  PooledThread* threadPtr = idleThreads.at( counter );
44  if (threadPtr != NULL)
45  {
46  delete threadPtr;
47  }
48  }
49  idleThreads.clear();
50 }
51 
53 {
54  Mutex::ScopedLock lock( dequeMutex );
55 
56  // are there any more idle threads?
57  if (idleThreads.size() == 0)
58  {
59  // check to see if any of the threads in the busy queue are actually idle
60  bool foundIdleThread = false;
61  std::deque<PooledThread*>::iterator iter;
62  for (iter = busyThreads.begin(); iter < busyThreads.end(); iter++)
63  {
64  PooledThread* threadPtr = *iter;
65  if ( !threadPtr->IsRunning() )
66  {
67  busyThreads.erase(iter);
68  idleThreads.push_back(threadPtr);
69  foundIdleThread = true;
70  }
71  }
72 
73  if ( !foundIdleThread )
74  {
75  idleThreads.push_back( new CLAM::PooledThread(this, mIsRealtime) );
76  }
77  }
78 
79  PooledThread* threadPtr = idleThreads.at(0);
80  idleThreads.pop_front();
81  busyThreads.push_back(threadPtr);
82 
83  return threadPtr;
84 }
85 
87 {
88  Mutex::ScopedLock lock( dequeMutex );
89 
90  std::deque<PooledThread*>::iterator iter = find ( busyThreads.begin(), busyThreads.end(), argThreadPtr );
91  busyThreads.erase( iter);
92 
93  idleThreads.push_back( argThreadPtr );
94 }
95 
96 } // end namespace CLAM