1 /* A thread pool (C++ version). */
3 /* Copyright (c) 2004-2020 The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
11 #include "src/internal_config.h" // HAVE_FUTEX_H
12 #include "src/kernel/context/Context.hpp"
13 #include "src/simix/smx_private.hpp" /* simix_global */
15 #include <boost/optional.hpp>
16 #include <condition_variable>
22 #include <linux/futex.h>
23 #include <sys/syscall.h>
27 #include <pthread_np.h>
30 XBT_LOG_EXTERNAL_CATEGORY(xbt_parmap);
35 /** @addtogroup XBT_parmap
37 * @brief Parallel map class
40 template <typename T> class Parmap {
42 Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode);
43 Parmap(const Parmap&) = delete;
44 Parmap& operator=(const Parmap&) = delete;
46 void apply(std::function<void(T)>&& fun, const std::vector<T>& data);
47 boost::optional<T> next();
51 * @brief Thread data transmission structure
55 ThreadData(Parmap<T>& parmap, int id) : parmap(parmap), worker_id(id) {}
61 * @brief Synchronization object (different specializations).
65 explicit Synchro(Parmap<T>& parmap) : parmap(parmap) {}
66 virtual ~Synchro() = default;
68 * @brief Wakes all workers and waits for them to finish the tasks.
70 * This function is called by the controller thread.
72 virtual void master_signal() = 0;
74 * @brief Starts the parmap: waits for all workers to be ready and returns.
76 * This function is called by the controller thread.
78 virtual void master_wait() = 0;
80 * @brief Ends the parmap: wakes the controller thread when all workers terminate.
82 * This function is called by all worker threads when they end (not including the controller).
84 virtual void worker_signal() = 0;
86 * @brief Waits for some work to process.
88 * This function is called by each worker thread (not including the controller) when it has no more work to do.
90 * @param round the expected round number
92 virtual void worker_wait(unsigned) = 0;
97 class PosixSynchro : public Synchro {
99 explicit PosixSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
100 void master_signal() override;
101 void master_wait() override;
102 void worker_signal() override;
103 void worker_wait(unsigned round) override;
106 std::condition_variable ready_cond;
107 std::mutex ready_mutex;
108 std::condition_variable done_cond;
109 std::mutex done_mutex;
113 class FutexSynchro : public Synchro {
115 explicit FutexSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
116 void master_signal() override;
117 void master_wait() override;
118 void worker_signal() override;
119 void worker_wait(unsigned) override;
122 static void futex_wait(std::atomic_uint* uaddr, unsigned val);
123 static void futex_wake(std::atomic_uint* uaddr, unsigned val);
127 class BusyWaitSynchro : public Synchro {
129 explicit BusyWaitSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
130 void master_signal() override;
131 void master_wait() override;
132 void worker_signal() override;
133 void worker_wait(unsigned) override;
136 static void worker_main(ThreadData* data);
137 Synchro* new_synchro(e_xbt_parmap_mode_t mode);
140 bool destroying = false; /**< is the parmap being destroyed? */
141 std::atomic_uint work_round{0}; /**< index of the current round */
142 std::vector<std::thread*> workers; /**< worker thread handlers */
143 unsigned num_workers; /**< total number of worker threads including the controller */
144 Synchro* synchro; /**< synchronization object */
146 std::atomic_uint thread_counter{0}; /**< number of workers that have done the work */
147 std::function<void(T)> fun; /**< function to run in parallel on each element of data */
148 const std::vector<T>* data = nullptr; /**< parameters to pass to fun in parallel */
149 std::atomic_uint index{0}; /**< index of the next element of data to pick */
153 * @brief Creates a parallel map object
154 * @param num_workers number of worker threads to create
155 * @param mode how to synchronize the worker threads
157 template <typename T> Parmap<T>::Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode)
159 XBT_CDEBUG(xbt_parmap, "Create new parmap (%u workers)", num_workers);
161 /* Initialize the thread pool data structure */
162 this->workers.resize(num_workers);
163 this->num_workers = num_workers;
164 this->synchro = new_synchro(mode);
166 /* Create the pool of worker threads (the caller of apply() will be worker[0]) */
167 this->workers[0] = nullptr;
169 for (unsigned i = 1; i < num_workers; i++) {
170 auto* data = new ThreadData(*this, i);
171 this->workers[i] = new std::thread(worker_main, data);
173 /* Bind the worker to a core if possible */
174 #if HAVE_PTHREAD_SETAFFINITY
175 #if HAVE_PTHREAD_NP_H /* FreeBSD ? */
177 size_t size = sizeof(cpuset_t);
180 size_t size = sizeof(cpu_set_t);
182 pthread_t pthread = this->workers[i]->native_handle();
183 int core_bind = (i - 1) % std::thread::hardware_concurrency();
185 CPU_SET(core_bind, &cpuset);
186 pthread_setaffinity_np(pthread, size, &cpuset);
192 * @brief Destroys a parmap
194 template <typename T> Parmap<T>::~Parmap()
197 synchro->master_signal();
199 for (unsigned i = 1; i < num_workers; i++) {
207 * @brief Applies a list of tasks in parallel.
208 * @param fun the function to call in parallel
209 * @param data each element of this vector will be passed as an argument to fun
211 template <typename T> void Parmap<T>::apply(std::function<void(T)>&& fun, const std::vector<T>& data)
213 /* Assign resources to worker threads (we are maestro here)*/
214 this->fun = std::move(fun);
217 this->synchro->master_signal(); // maestro runs futex_wake to wake all the minions (the working threads)
218 this->work(); // maestro works with its minions
219 this->synchro->master_wait(); // When there is no more work to do, then maestro waits for the last minion to stop
220 XBT_CDEBUG(xbt_parmap, "Job done"); // ... and proceeds
224 * @brief Returns a next task to process.
226 * Worker threads call this function to get more work.
228 * @return the next task to process, or throws a std::out_of_range exception if there is no more work
230 template <typename T> boost::optional<T> Parmap<T>::next()
232 unsigned index = this->index.fetch_add(1, std::memory_order_relaxed);
233 if (index < this->data->size())
234 return (*this->data)[index];
240 * @brief Main work loop: applies fun to elements in turn.
242 template <typename T> void Parmap<T>::work()
244 unsigned length = this->data->size();
245 unsigned index = this->index.fetch_add(1, std::memory_order_relaxed);
246 while (index < length) {
247 this->fun((*this->data)[index]);
248 index = this->index.fetch_add(1, std::memory_order_relaxed);
253 * Get a synchronization object for given mode.
254 * @param mode the synchronization mode
256 template <typename T> typename Parmap<T>::Synchro* Parmap<T>::new_synchro(e_xbt_parmap_mode_t mode)
258 if (mode == XBT_PARMAP_DEFAULT) {
260 mode = XBT_PARMAP_FUTEX;
262 mode = XBT_PARMAP_POSIX;
267 case XBT_PARMAP_POSIX:
268 res = new PosixSynchro(*this);
270 case XBT_PARMAP_FUTEX:
272 res = new FutexSynchro(*this);
274 xbt_die("Futex is not available on this OS.");
277 case XBT_PARMAP_BUSY_WAIT:
278 res = new BusyWaitSynchro(*this);
286 /** @brief Main function of a worker thread */
287 template <typename T> void Parmap<T>::worker_main(ThreadData* data)
289 Parmap<T>& parmap = data->parmap;
291 kernel::context::Context* context = simix_global->context_factory->create_context(std::function<void()>(), nullptr);
292 kernel::context::Context::set_current(context);
294 XBT_CDEBUG(xbt_parmap, "New worker thread created");
296 /* Worker's main loop */
298 round++; // New scheduling round
299 parmap.synchro->worker_wait(round);
300 if (parmap.destroying)
303 XBT_CDEBUG(xbt_parmap, "Worker %d got a job", data->worker_id);
305 parmap.synchro->worker_signal();
306 XBT_CDEBUG(xbt_parmap, "Worker %d has finished", data->worker_id);
308 /* We are destroying the parmap */
313 template <typename T> void Parmap<T>::PosixSynchro::master_signal()
315 std::unique_lock<std::mutex> lk(ready_mutex);
316 this->parmap.thread_counter = 1;
317 this->parmap.work_round++;
318 /* wake all workers */
319 ready_cond.notify_all();
322 template <typename T> void Parmap<T>::PosixSynchro::master_wait()
324 std::unique_lock<std::mutex> lk(done_mutex);
325 /* wait for all workers to be ready */
326 done_cond.wait(lk, [this]() { return this->parmap.thread_counter >= this->parmap.num_workers; });
329 template <typename T> void Parmap<T>::PosixSynchro::worker_signal()
331 std::unique_lock<std::mutex> lk(done_mutex);
332 this->parmap.thread_counter++;
333 if (this->parmap.thread_counter == this->parmap.num_workers) {
334 /* all workers have finished, wake the controller */
335 done_cond.notify_one();
339 template <typename T> void Parmap<T>::PosixSynchro::worker_wait(unsigned round)
341 std::unique_lock<std::mutex> lk(ready_mutex);
342 /* wait for more work */
343 ready_cond.wait(lk, [this, round]() { return this->parmap.work_round == round; });
347 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wait(std::atomic_uint* uaddr, unsigned val)
349 XBT_CVERB(xbt_parmap, "Waiting on futex %p", uaddr);
350 syscall(SYS_futex, uaddr, FUTEX_WAIT_PRIVATE, val, nullptr, nullptr, 0);
353 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wake(std::atomic_uint* uaddr, unsigned val)
355 XBT_CVERB(xbt_parmap, "Waking futex %p", uaddr);
356 syscall(SYS_futex, uaddr, FUTEX_WAKE_PRIVATE, val, nullptr, nullptr, 0);
359 template <typename T> void Parmap<T>::FutexSynchro::master_signal()
361 this->parmap.thread_counter.store(1);
362 this->parmap.work_round.fetch_add(1);
363 /* wake all workers */
364 futex_wake(&this->parmap.work_round, std::numeric_limits<int>::max());
367 template <typename T> void Parmap<T>::FutexSynchro::master_wait()
369 unsigned count = this->parmap.thread_counter.load();
370 while (count < this->parmap.num_workers) {
371 /* wait for all workers to be ready */
372 futex_wait(&this->parmap.thread_counter, count);
373 count = this->parmap.thread_counter.load();
377 template <typename T> void Parmap<T>::FutexSynchro::worker_signal()
379 unsigned count = this->parmap.thread_counter.fetch_add(1) + 1;
380 if (count == this->parmap.num_workers) {
381 /* all workers have finished, wake the controller */
382 futex_wake(&this->parmap.thread_counter, std::numeric_limits<int>::max());
386 template <typename T> void Parmap<T>::FutexSynchro::worker_wait(unsigned round)
388 unsigned work_round = this->parmap.work_round.load();
389 /* wait for more work */
390 while (work_round != round) {
391 futex_wait(&this->parmap.work_round, work_round);
392 work_round = this->parmap.work_round.load();
397 template <typename T> void Parmap<T>::BusyWaitSynchro::master_signal()
399 this->parmap.thread_counter.store(1);
400 this->parmap.work_round.fetch_add(1);
403 template <typename T> void Parmap<T>::BusyWaitSynchro::master_wait()
405 while (this->parmap.thread_counter.load() < this->parmap.num_workers) {
406 std::this_thread::yield();
410 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_signal()
412 this->parmap.thread_counter.fetch_add(1);
415 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_wait(unsigned round)
417 /* wait for more work */
418 while (this->parmap.work_round.load() != round) {
419 std::this_thread::yield();