Tissue Forge C++ 0.2.1
Interactive, particle-based physics, chemistry and biology modeling and simulation environment
Loading...
Searching...
No Matches
tfThreadPool.h
1/*******************************************************************************
2 * This file is part of Tissue Forge.
3 * Copyright (c) 2022-2024 T.J. Sego
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published
7 * by the Free Software Foundation, either version 3 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 Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 ******************************************************************************/
19
20/*
21 Based on Magnum example
22
23 Original authors — credit is appreciated but not required:
24
25 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
26 Vladimír Vondruš <mosra@centrum.cz>
27 2019 — Nghia Truong <nghiatruong.vn@gmail.com>
28
29 This library is free software; you can redistribute it and/or
30 modify it under the terms of the GNU Lesser General Public
31 License as published by the Free Software Foundation; either
32 version 2.1 of the License, or (at your option) any later version.
33
34 This library is distributed in the hope that it will be useful,
35 but WITHOUT ANY WARRANTY; without even the implied warranty of
36 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
37 Lesser General Public License for more details.
38 */
39
40#ifndef _SOURCE_TFTHREADPOOL_H_
41#define _SOURCE_TFTHREADPOOL_H_
42
43#include <vector>
44#include <thread>
45#include <mutex>
46#include <condition_variable>
47#include <functional>
48#include <atomic>
49#include <Magnum/Math/Functions.h>
50
51
52namespace TissueForge {
53
54
55 /* This is a very simple threadpool implementation, for demonstration purpose
56 only. Using tbb::parallel_for from Intel TBB yields higher performance --
57 see TaskScheduler.h. */
58 class ThreadPool {
59 public:
60 ThreadPool() {
61 const int maxNumThreads = std::thread::hardware_concurrency();
62 std::size_t nWorkers = maxNumThreads > 1 ? maxNumThreads - 1 : 0;
63
64 _threadTaskReady.resize(nWorkers, 0);
65 _tasks.resize(nWorkers + 1);
66
67 for(std::size_t threadIdx = 0; threadIdx < nWorkers; ++threadIdx) {
68 _workerThreads.emplace_back([threadIdx, this] {
69 for(;;) {
70 {
71 std::unique_lock<std::mutex> lock(_taskMutex);
72 _condition.wait(lock, [threadIdx, this] {
73 return _bStop || _threadTaskReady[threadIdx] == 1;
74 });
75 if(_bStop && !_threadTaskReady[threadIdx]) return;
76 }
77
78 _tasks[threadIdx](); /* run task */
79
80 /* Set task ready to 0, thus this thread will not do
81 its computation more than once */
82 _threadTaskReady[threadIdx] = 0;
83
84 /* Decrease the busy thread counter */
85 _numBusyThreads.fetch_add(-1);
86 }
87 });
88 }
89 }
90
91 ~ThreadPool() {
92 {
93 std::unique_lock<std::mutex> lock(_taskMutex);
94 _bStop = true;
95 }
96
97 _condition.notify_all();
98 for(std::thread& worker: _workerThreads) worker.join();
99 }
100
101 void parallel_for(std::size_t size, std::function<void(std::size_t)>&& func) {
102 const auto nWorkers = _workerThreads.size();
103 if(nWorkers > 0) {
104 _numBusyThreads = int(nWorkers);
105
106 const std::size_t chunkSize = std::size_t(Magnum::Math::ceil(float(size)/ float(nWorkers + 1)));
107 for(std::size_t threadIdx = 0; threadIdx < nWorkers + 1; ++threadIdx) {
108 const std::size_t chunkStart = threadIdx * chunkSize;
109 const std::size_t chunkEnd = Magnum::Math::min(chunkStart + chunkSize, size);
110
111 /* Must copy func into local lambda's variable */
112 _tasks[threadIdx] = [chunkStart, chunkEnd, task = func] {
113 for(uint64_t idx = chunkStart; idx < chunkEnd; ++idx) {
114 task(idx);
115 }
116 };
117 }
118
119 /* Wake up worker threads */
120 {
121 std::unique_lock<std::mutex> lock(_taskMutex);
122 for(std::size_t threadIdx = 0; threadIdx < _threadTaskReady.size(); ++threadIdx)
123 _threadTaskReady[threadIdx] = 1;
124 }
125 _condition.notify_all();
126
127 /* Handle last chunk in this thread */
128 _tasks.back()();
129
130 /* Wait until all worker threads finish */
131 while(_numBusyThreads.load() > 0) {}
132
133 } else for(std::size_t idx = 0; idx < size; ++idx)
134 func(idx);
135 }
136
137 static ThreadPool& getUniqueInstance() {
138 static ThreadPool threadPool;
139 return threadPool;
140 }
141
142 static int hardwareThreadSize() {
143 return std::thread::hardware_concurrency();
144 }
145
146 static int size() {
147 return getUniqueInstance()._workerThreads.size();
148 }
149
150 private:
151 std::atomic<int> _numBusyThreads{0};
152 /* Do not use std::vector<bool>: it's not threadsafe */
153 std::vector<int> _threadTaskReady;
154 std::vector<std::thread> _workerThreads;
155
156 std::vector<std::function<void()>> _tasks;
157 std::mutex _taskMutex;
158 std::condition_variable _condition;
159 bool _bStop = false;
160 };
161}
162
163#endif // _SOURCE_TFTHREADPOOL_H_
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode.
Definition tfAngleConfig.h:26
struct TissueForge::task task
Definition tfTask.h:60