Audaspace  1.4.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 #include <functional>
34 
40 {
41 private:
45  std::queue<std::function<void()>> m_queue;
46 
50  std::vector<std::thread> m_threads;
51 
55  std::mutex m_mutex;
56 
60  std::condition_variable m_condition;
61 
65  bool m_stopFlag;
66 
70  unsigned int m_numThreads;
71 
72  // delete copy constructor and operator=
73  ThreadPool(const ThreadPool&) = delete;
74  ThreadPool& operator=(const ThreadPool&) = delete;
75 public:
80  ThreadPool(unsigned int count);
81 
82  virtual ~ThreadPool();
83 
90  template<class T, class... Args>
91  std::future<typename std::result_of<T(Args...)>::type> enqueue(T&& t, Args&&... args)
92  {
93  using pkgdTask = std::packaged_task<typename std::result_of<T(Args...)>::type()>;
94 
95  std::shared_ptr<pkgdTask> task = std::make_shared<pkgdTask>(std::bind(std::forward<T>(t), std::forward<Args>(args)...));
96  auto result = task->get_future();
97 
98  m_mutex.lock();
99  m_queue.emplace([task]() { (*task)(); });
100  m_mutex.unlock();
101 
102  m_condition.notify_one();
103  return result;
104  }
105 
110  unsigned int getNumOfThreads();
111 
112 private:
113 
117  void threadFunction();
118 };
#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:39
#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:91
The main header file of the library defining the namespace and basic data types.