Audaspace  1.3.0
A high level audio library.
ThreadPool.h
Go to the documentation of this file.
1 /*******************************************************************************
2 * Copyright 2015-2016 Juan Francisco Crespo Galán
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 ******************************************************************************/
16 
17 #pragma once
18 
25 #include "Audaspace.h"
26 
27 #include <mutex>
28 #include <condition_variable>
29 #include <vector>
30 #include <thread>
31 #include <queue>
32 #include <future>
33 
39 {
40 private:
44  std::queue<std::function<void()>> m_queue;
45 
49  std::vector<std::thread> m_threads;
50 
54  std::mutex m_mutex;
55 
59  std::condition_variable m_condition;
60 
64  bool m_stopFlag;
65 
69  unsigned int m_numThreads;
70 
71  // delete copy constructor and operator=
72  ThreadPool(const ThreadPool&) = delete;
73  ThreadPool& operator=(const ThreadPool&) = delete;
74 public:
79  ThreadPool(unsigned int count);
80 
81  virtual ~ThreadPool();
82 
89  template<class T, class... Args>
90  std::future<typename std::result_of<T(Args...)>::type> enqueue(T&& t, Args&&... args)
91  {
92  using pkgdTask = std::packaged_task<typename std::result_of<T(Args...)>::type()>;
93 
94  std::shared_ptr<pkgdTask> task = std::make_shared<pkgdTask>(std::bind(std::forward<T>(t), std::forward<Args>(args)...));
95  auto result = task->get_future();
96 
97  m_mutex.lock();
98  m_queue.emplace([task]() { (*task)(); });
99  m_mutex.unlock();
100 
101  m_condition.notify_one();
102  return result;
103  }
104 
109  unsigned int getNumOfThreads();
110 
111 private:
112 
116  void threadFunction();
117 };
#define AUD_NAMESPACE_BEGIN
Opens the audaspace namespace aud.
Definition: Audaspace.h:116
#define AUD_API
Used for exporting symbols in the shared library.
Definition: Audaspace.h:93
This represents pool of threads.
Definition: ThreadPool.h:38
#define AUD_NAMESPACE_END
Closes the audaspace namespace aud.
Definition: Audaspace.h:119
std::future< typename std::result_of< T(Args...)>::type > enqueue(T &&t, Args &&... args)
Enqueues a new task for the threads to realize.
Definition: ThreadPool.h:90
The main header file of the library defining the namespace and basic data types.