GestureRecognitionToolkit  Version: 0.2.5
The Gesture Recognition Toolkit (GRT) is a cross-platform, open-source, c++ machine learning library for real-time gesture recognition.
ThreadPool.cpp
1 #define GRT_DLL_EXPORTS
2 #include "ThreadPool.h"
3 #include <iostream>
4 
5 using namespace GRT;
6 
7 #ifdef GRT_CXX11_ENABLED
8 //Initalize the static thread pool size to the systems suggested thread limit
9 std::atomic< unsigned int > ThreadPool::threadPoolSize( std::thread::hardware_concurrency() );
10 #endif
11 
13 {
14 #ifdef GRT_CXX11_ENABLED
15  stop = false;
16  launchThreads( threadPoolSize );
17 #endif
18 }
19 
20 ThreadPool::ThreadPool(const unsigned int poolSize)
21 {
22 #ifdef GRT_CXX11_ENABLED
23  stop = false;
24  launchThreads( poolSize );
25 #endif
26 }
27 
28 // the destructor joins all threads
30 {
31 std::cout << "~ThreadPool()\n";
32 #ifdef GRT_CXX11_ENABLED
33  stop = true;
34  condition.notify_all();
35  for(std::thread &worker: workers)
36  worker.join();
37 #endif
38 }
39 
40 #ifdef GRT_CXX11_ENABLED
41 void ThreadPool::launchThreads( const unsigned int poolSize ){
42 
43  //Start the worker thread, each thread will wait for incoming tasks and pop them off the queue when ready
44  for(unsigned int i = 0; i<poolSize; ++i)
45  workers.emplace_back(
46  [this]
47  {
48  while( true )
49  {
50  std::function< void() > task;
51 
52  //Lock the queue and wait for the condition to change
53  {
54  std::unique_lock<std::mutex> lock(this->queue_mutex);
55  this->condition.wait(lock,
56  [this]{ return this->stop || !this->tasks.empty(); });
57  if(this->stop && this->tasks.empty()){
58  std::cout << "stopping worker!" << std::endl;
59  return;
60  }
61  task = std::move(this->tasks.front());
62  this->tasks.pop();
63  }
64 
65 
66  //Otherwise grab the task from the front of the buffer
67  if( task ){
68  //Run the task
69  task();
70  }
71 
72  }
73  }
74  );
75 }
76 #endif
77 
79 #ifdef GRT_CXX11_ENABLED
80  return threadPoolSize;
81 #else
82  return 0;
83 #endif
84 }
85 
86 bool ThreadPool::setThreadPoolSize( const unsigned int threadPoolSize_ ){
87 #ifdef GRT_CXX11_ENABLED
88  threadPoolSize = threadPoolSize_;
89  return true;
90 #else
91  return false;
92 #endif
93 }
94 
static unsigned int getThreadPoolSize()
Definition: ThreadPool.cpp:78
The ThreadPool class implements a flexible inteface for performing a large number of batch tasks...
static bool setThreadPoolSize(const unsigned int threadPoolSize)
Definition: ThreadPool.cpp:86