Debian Codegraph @

src/engine/workPool.h

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifndef _WORKPOOL_H
21 #define _WORKPOOL_H
22
23 #include <thread>
24 #include <atomic>
25 #include <functional>
26 #include <future>
27
28 #include "../fixedQueue.h"
29
30 class DivWorkPool;
31
32 struct DivPendingTask {
33 void (*func)(void*);
34 void* funcArg;
35 DivPendingTask(void (*f)(void*), void* arg):
36 func(f),
37 funcArg(arg) {}
38 DivPendingTask():
39 func(NULL),
40 funcArg(NULL) {}
41 };
42
43 struct DivWorkThread {
44 DivWorkPool* parent;
45 std::mutex lock;
46 std::thread* thread;
47 std::promise<void> notify;
48 FixedQueue<DivPendingTask,32> tasks;
49 std::atomic<bool> isBusy;
50 bool terminate;
51 bool promiseAlreadySet;
52
53 void run();
54 bool assign(void (*what)(void*), void* arg);
55 void wait();
56 bool busy();
57 void finish();
58
59 bool init(DivWorkPool* p);
60 DivWorkThread():
61 parent(NULL),
62 isBusy(false),
63 terminate(false),
64 promiseAlreadySet(false) {}
65 };
66
67 /**
68 * this class provides an implementation of a "thread pool" for executing tasks in parallel.
69 * it is highly recommended to use `new` when allocating a DivWorkPool.
70 */
71 class DivWorkPool {
72 bool threaded;
73 unsigned int count;
74 unsigned int pos;
75 DivWorkThread* workThreads;
76 public:
77 std::promise<void> notify;
78 std::atomic<int> busyCount;
79
80 /**
81 * push a new job to this work pool.
82 * if all work threads are busy, this will block until one is free.
83 */
84 void push(void (*what)(void*), void* arg);
85
86 /**
87 * check whether this work pool is busy.
88 */
89 bool busy();
90
91 /**
92 * wait for all work threads to finish.
93 */
94 void wait();
95
96 DivWorkPool(unsigned int threads=0);
97 ~DivWorkPool();
98 };
99
100 #endif