Voxellancer  0.3
A game about voxels in space
 All Classes Functions Pages
threadpool.h
1 #pragma once
2 
3 #include <vector>
4 #include <thread>
5 #include <condition_variable>
6 #include <mutex>
7 #include <atomic>
8 
9 /*
10  The threadpool allows to distribute work to multiple threads.
11  The works needs a function f(x) and a vector<x>. f gets executed
12  for every value in vector.
13  The threadpool uses conditionvariables and atomic_ints to communicate.
14 */
15 template<typename T>
16 class ThreadPool {
17 public:
18  ThreadPool(int threadcount = 4, int chunksize = 100);
19  ~ThreadPool();
20 
21  // calls function(element) for every element in data
22  void map(std::function<void(T&)> function, std::vector<T>& data);
23  // calls a function(element) for every element in data[start:end] (inclusive start, exclusive end)
24  void map(std::function<void(T&)> function, std::vector<T>& data, int start, int end);
25 
26 protected:
27  void startWorkers();
28  void worker();
29  int getTask();
30 
31  std::vector<T>* m_tasks;
32  std::function<void(T&)> m_function;
33 
34  std::vector<std::thread> m_workers;
35  std::condition_variable m_startSignal;
36  std::condition_variable m_stopSignal;
37  std::mutex m_mutex;
38 
39  std::atomic_int m_currentIndex;
40  int m_endIndex;
41  int m_chunksize;
42 
43  bool m_exit;
44  std::atomic_int m_startWorkers;
45  std::atomic_int m_stoppedWorkers;
46 
47 };
48 
49 #include "threadpool.inl"
Definition: threadpool.h:16