summaryrefslogtreecommitdiffstats
path: root/extra/mariabackup/thread_pool.h
blob: 10ad74c6220e453b63c95b6f295c9cbfa0169a8a (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
62
#pragma once
#include <queue>
#include <vector>
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include "trx0sys.h"

class ThreadPool {
public:
	typedef std::function<void(unsigned)> job_t;

	ThreadPool() { m_stop = false; m_stopped = true; }
	ThreadPool (ThreadPool &&other) = delete;
	ThreadPool &  operator= (ThreadPool &&other) = delete;
	ThreadPool(const ThreadPool &) = delete;
	ThreadPool & operator= (const ThreadPool &) = delete;

	bool start(size_t threads_count);
	void stop();
	void push(job_t &&j);
	size_t threads_count() const { return m_threads.size(); }
private:
	void thread_func(unsigned thread_num);
	std::mutex m_mutex;
	std::condition_variable m_cv;
	std::queue<job_t> m_jobs;
	std::atomic<bool> m_stop;
	std::atomic<bool> m_stopped;
	std::vector<std::thread> m_threads;
};

class TasksGroup {
public:
	TasksGroup(ThreadPool &thread_pool) : m_thread_pool(thread_pool) {
		m_tasks_count = 0;
		m_tasks_result = 1;
	}
	void push_task(ThreadPool::job_t &&j) {
		++m_tasks_count;
		m_thread_pool.push(std::forward<ThreadPool::job_t>(j));
	}
	void finish_task(int res) {
		--m_tasks_count;
		m_tasks_result.fetch_and(res);
	}
	int get_result() const { return m_tasks_result; }
	bool is_finished() const {
		return !m_tasks_count;
	}
	bool wait_for_finish() {
		while (!is_finished())
                        std::this_thread::sleep_for(std::chrono::milliseconds(1));
		return get_result();
	}
private:
	ThreadPool &m_thread_pool;
	std::atomic<size_t> m_tasks_count;
	std::atomic<int> m_tasks_result;
};