summaryrefslogtreecommitdiff
path: root/lib/worker.h
blob: 04e351b8c0ac37fb295e6b2ee80a53450d74b986 (plain)
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
#ifndef WORKER_H
#define WORKER_H

#include <utility>

#if __cpp_lib_semaphore
#	include <deque>
#	include <memory>
#	include <mutex>
#	include <semaphore>
#	include <special_members.hpp>
#	include <thread>
#	include <vector>

class Work;

class Worker {
public:
	Worker();
	~Worker();

	NO_COPY(Worker);
	NO_MOVE(Worker);

	using WorkPtr = std::unique_ptr<Work>;

	template<typename T, typename... Params>
	void
	addWork(Params &&... params)
	{
		addWork(std::make_unique<T>(std::forward<Params>(params)...));
	}

	void addWork(WorkPtr w);

private:
	void worker();

	using Threads = std::vector<std::thread>;
	using ToDo = std::deque<WorkPtr>;

	Threads threads;
	ToDo todo;
	std::counting_semaphore<16> todoLen;
	std::mutex todoMutex;
};

#else

class Worker {
public:
	template<typename T, typename... Params>
	void
	addWork(Params &&... params)
	{
		T(std::forward<Params>(params)...).doWork();
	}
};

#endif
#endif