File: threadpool.h

package info (click to toggle)
wsclean 2.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,196 kB
  • sloc: cpp: 34,504; ansic: 234; python: 174; makefile: 10
file content (93 lines) | stat: -rw-r--r-- 1,617 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include "system.h"

#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>

#include <queue>

class ThreadPool
{
public:
	ThreadPool() : _activeThreads(0), _finish(false)
	{
		init_threads(System::ProcessorCount());
	}
	
	~ThreadPool()
	{
		std::unique_lock<std::mutex> lock(_mutex);
		_finish = true;
		_change.notify_all();
		lock.unlock();
		for(size_t i=0; i!=_threads.size(); ++i)
		{
			_threads[i].join();
		}
	}
	
	template<typename func>
	void queue(func f)
	{
		std::lock_guard<std::mutex> lock(_mutex);
		_queuedTasks.push(f);
		_change.notify_all();
	}
	
	void wait_for_all_tasks()
	{
		std::unique_lock<std::mutex> lock(_mutex);
		while(_activeThreads!=0 || !_queuedTasks.empty())
			_change.wait(lock);
	}
	
	size_t size() const { return _threads.size(); }
	
private:
	void init_threads(size_t n)
	{
		_threads.resize(n);
		for(size_t i=0; i!=n; ++i)
		{
			_threads[i] = std::thread(
				std::mem_fun(&ThreadPool::thread_function), this);
		}
	}
	
	void thread_function()
	{
		std::unique_lock<std::mutex> lock(_mutex);
		while(!_finish)
		{
			while(_queuedTasks.empty() && !_finish)
				_change.wait(lock);
			
			if(!_finish)
			{
				++_activeThreads;
				auto f = _queuedTasks.front();
				_queuedTasks.pop();
				lock.unlock();
				f();
				lock.lock();
				--_activeThreads;
				
				_change.notify_all();
			}
		}
	}
	
	std::vector<std::thread> _threads;
	std::size_t _activeThreads;
	std::queue<std::function<void()> > _queuedTasks;
	bool _finish;
	
	std::mutex _mutex;
	std::condition_variable _change;
};

#endif