1// LAF Base Library
2// Copyright (C) 2019-2022 Igara Studio S.A.
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#ifndef BASE_THREAD_POOL_H_INCLUDED
8#define BASE_THREAD_POOL_H_INCLUDED
9#pragma once
10
11#include <condition_variable>
12#include <functional>
13#include <mutex>
14#include <queue>
15#include <thread> // We want to replace base::thread with base::thread
16#include <vector>
17
18namespace base {
19
20 class thread_pool {
21 public:
22 thread_pool(const size_t n);
23 ~thread_pool();
24
25 void execute(std::function<void()>&& func);
26
27 // Waits until the queue is empty.
28 void wait_all();
29
30 private:
31 // Joins all threads without waiting the queue to be processed.
32 void join_all();
33
34 // Called for each worker thread.
35 void worker();
36
37 bool m_running;
38 std::vector<std::thread> m_threads;
39 std::mutex m_mutex;
40 std::condition_variable m_cv;
41 std::condition_variable m_cvWait;
42 std::queue<std::function<void()>> m_work;
43 int m_doingWork;
44 };
45
46}
47
48#endif
49