1 /* A thread pool (C++ version). */
3 /* Copyright (c) 2004-2018 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 "xbt/xbt_os_thread.h"
15 #include <boost/optional.hpp>
16 #include <condition_variable>
21 #include <linux/futex.h>
22 #include <sys/syscall.h>
25 XBT_LOG_EXTERNAL_CATEGORY(xbt_parmap);
30 /** @addtogroup XBT_parmap
32 * @brief Parallel map class
35 template <typename T> class Parmap {
37 Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode);
38 Parmap(const Parmap&) = delete;
39 Parmap& operator=(const Parmap&) = delete;
41 void apply(void (*fun)(T), const std::vector<T>& data);
42 boost::optional<T> next();
45 enum Flag { PARMAP_WORK, PARMAP_DESTROY };
48 * @brief Thread data transmission structure
52 ThreadData(Parmap<T>& parmap, int id) : parmap(parmap), worker_id(id) {}
58 * @brief Synchronization object (different specializations).
62 explicit Synchro(Parmap<T>& parmap) : parmap(parmap) {}
63 virtual ~Synchro() = default;
65 * @brief Wakes all workers and waits for them to finish the tasks.
67 * This function is called by the controller thread.
69 virtual void master_signal() = 0;
71 * @brief Starts the parmap: waits for all workers to be ready and returns.
73 * This function is called by the controller thread.
75 virtual void master_wait() = 0;
77 * @brief Ends the parmap: wakes the controller thread when all workers terminate.
79 * This function is called by all worker threads when they end (not including the controller).
81 virtual void worker_signal() = 0;
83 * @brief Waits for some work to process.
85 * This function is called by each worker thread (not including the controller) when it has no more work to do.
87 * @param round the expected round number
89 virtual void worker_wait(unsigned) = 0;
94 class PosixSynchro : public Synchro {
96 explicit PosixSynchro(Parmap<T>& parmap);
100 void worker_signal();
101 void worker_wait(unsigned round);
104 std::condition_variable ready_cond;
105 std::mutex ready_mutex;
106 std::condition_variable done_cond;
107 std::mutex done_mutex;
111 class FutexSynchro : public Synchro {
113 explicit FutexSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
114 void master_signal();
116 void worker_signal();
117 void worker_wait(unsigned);
120 static void futex_wait(unsigned* uaddr, unsigned val);
121 static void futex_wake(unsigned* uaddr, unsigned val);
125 class BusyWaitSynchro : public Synchro {
127 explicit BusyWaitSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
128 void master_signal();
130 void worker_signal();
131 void worker_wait(unsigned);
134 static void* worker_main(void* arg);
135 Synchro* new_synchro(e_xbt_parmap_mode_t mode);
138 Flag status; /**< is the parmap active or being destroyed? */
139 unsigned work_round; /**< index of the current round */
140 xbt_os_thread_t* workers; /**< worker thread handlers */
141 unsigned num_workers; /**< total number of worker threads including the controller */
142 Synchro* synchro; /**< synchronization object */
144 unsigned thread_counter = 0; /**< number of workers that have done the work */
145 void (*fun)(const T) = nullptr; /**< function to run in parallel on each element of data */
146 const std::vector<T>* data = nullptr; /**< parameters to pass to fun in parallel */
147 std::atomic<unsigned> index; /**< index of the next element of data to pick */
151 * @brief Creates a parallel map object
152 * @param num_workers number of worker threads to create
153 * @param mode how to synchronize the worker threads
155 template <typename T> Parmap<T>::Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode)
157 XBT_CDEBUG(xbt_parmap, "Create new parmap (%u workers)", num_workers);
159 /* Initialize the thread pool data structure */
160 this->status = PARMAP_WORK;
161 this->work_round = 0;
162 this->workers = new xbt_os_thread_t[num_workers];
163 this->num_workers = num_workers;
164 this->synchro = new_synchro(mode);
166 /* Create the pool of worker threads */
167 this->workers[0] = nullptr;
168 #if HAVE_PTHREAD_SETAFFINITY
171 for (unsigned i = 1; i < num_workers; i++) {
172 ThreadData* data = new ThreadData(*this, i);
173 this->workers[i] = xbt_os_thread_create(nullptr, worker_main, data, nullptr);
174 #if HAVE_PTHREAD_SETAFFINITY
175 xbt_os_thread_bind(this->workers[i], core_bind);
176 if (core_bind != xbt_os_get_numcores() - 1)
185 * @brief Destroys a parmap
187 template <typename T> Parmap<T>::~Parmap()
189 status = PARMAP_DESTROY;
190 synchro->master_signal();
192 for (unsigned i = 1; i < num_workers; i++)
193 xbt_os_thread_join(workers[i], nullptr);
200 * @brief Applies a list of tasks in parallel.
201 * @param fun the function to call in parallel
202 * @param data each element of this vector will be passed as an argument to fun
204 template <typename T> void Parmap<T>::apply(void (*fun)(T), const std::vector<T>& data)
206 /* Assign resources to worker threads (we are maestro here)*/
210 this->synchro->master_signal(); // maestro runs futex_wake to wake all the minions (the working threads)
211 this->work(); // maestro works with its minions
212 this->synchro->master_wait(); // When there is no more work to do, then maestro waits for the last minion to stop
213 XBT_CDEBUG(xbt_parmap, "Job done"); // ... and proceeds
217 * @brief Returns a next task to process.
219 * Worker threads call this function to get more work.
221 * @return the next task to process, or throws a std::out_of_range exception if there is no more work
223 template <typename T> boost::optional<T> Parmap<T>::next()
225 unsigned index = this->index.fetch_add(1, std::memory_order_relaxed);
226 if (index < this->data->size())
227 return (*this->data)[index];
233 * @brief Main work loop: applies fun to elements in turn.
235 template <typename T> void Parmap<T>::work()
237 unsigned length = this->data->size();
238 unsigned index = this->index.fetch_add(1, std::memory_order_relaxed);
239 while (index < length) {
240 this->fun((*this->data)[index]);
241 index = this->index.fetch_add(1, std::memory_order_relaxed);
246 * Get a synchronization object for given mode.
247 * @param mode the synchronization mode
249 template <typename T> typename Parmap<T>::Synchro* Parmap<T>::new_synchro(e_xbt_parmap_mode_t mode)
251 if (mode == XBT_PARMAP_DEFAULT) {
253 mode = XBT_PARMAP_FUTEX;
255 mode = XBT_PARMAP_POSIX;
260 case XBT_PARMAP_POSIX:
261 res = new PosixSynchro(*this);
263 case XBT_PARMAP_FUTEX:
265 res = new FutexSynchro(*this);
267 xbt_die("Futex is not available on this OS.");
270 case XBT_PARMAP_BUSY_WAIT:
271 res = new BusyWaitSynchro(*this);
280 * @brief Main function of a worker thread.
282 template <typename T> void* Parmap<T>::worker_main(void* arg)
284 ThreadData* data = static_cast<ThreadData*>(arg);
285 Parmap<T>& parmap = data->parmap;
287 smx_context_t context = SIMIX_context_new(std::function<void()>(), nullptr, nullptr);
288 SIMIX_context_set_current(context);
290 XBT_CDEBUG(xbt_parmap, "New worker thread created");
292 /* Worker's main loop */
295 parmap.synchro->worker_wait(round);
296 if (parmap.status == PARMAP_DESTROY)
299 XBT_CDEBUG(xbt_parmap, "Worker %d got a job", data->worker_id);
301 parmap.synchro->worker_signal();
302 XBT_CDEBUG(xbt_parmap, "Worker %d has finished", data->worker_id);
304 /* We are destroying the parmap */
310 template <typename T> Parmap<T>::PosixSynchro::PosixSynchro(Parmap<T>& parmap) : Synchro(parmap)
314 template <typename T> Parmap<T>::PosixSynchro::~PosixSynchro()
318 template <typename T> void Parmap<T>::PosixSynchro::master_signal()
320 std::unique_lock<std::mutex> lk(ready_mutex);
321 this->parmap.thread_counter = 1;
322 this->parmap.work_round++;
323 /* wake all workers */
324 ready_cond.notify_all();
327 template <typename T> void Parmap<T>::PosixSynchro::master_wait()
329 std::unique_lock<std::mutex> lk(done_mutex);
330 while (this->parmap.thread_counter < this->parmap.num_workers) {
331 /* wait for all workers to be ready */
336 template <typename T> void Parmap<T>::PosixSynchro::worker_signal()
338 std::unique_lock<std::mutex> lk(done_mutex);
339 this->parmap.thread_counter++;
340 if (this->parmap.thread_counter == this->parmap.num_workers) {
341 /* all workers have finished, wake the controller */
342 done_cond.notify_one();
346 template <typename T> void Parmap<T>::PosixSynchro::worker_wait(unsigned round)
348 std::unique_lock<std::mutex> lk(ready_mutex);
349 /* wait for more work */
350 while (this->parmap.work_round != round) {
356 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wait(unsigned* uaddr, unsigned val)
358 XBT_CVERB(xbt_parmap, "Waiting on futex %p", uaddr);
359 syscall(SYS_futex, uaddr, FUTEX_WAIT_PRIVATE, val, nullptr, nullptr, 0);
362 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wake(unsigned* uaddr, unsigned val)
364 XBT_CVERB(xbt_parmap, "Waking futex %p", uaddr);
365 syscall(SYS_futex, uaddr, FUTEX_WAKE_PRIVATE, val, nullptr, nullptr, 0);
368 template <typename T> void Parmap<T>::FutexSynchro::master_signal()
370 __atomic_store_n(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
371 __atomic_add_fetch(&this->parmap.work_round, 1, __ATOMIC_SEQ_CST);
372 /* wake all workers */
373 futex_wake(&this->parmap.work_round, std::numeric_limits<int>::max());
376 template <typename T> void Parmap<T>::FutexSynchro::master_wait()
378 unsigned count = __atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST);
379 while (count < this->parmap.num_workers) {
380 /* wait for all workers to be ready */
381 futex_wait(&this->parmap.thread_counter, count);
382 count = __atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST);
386 template <typename T> void Parmap<T>::FutexSynchro::worker_signal()
388 unsigned count = __atomic_add_fetch(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
389 if (count == this->parmap.num_workers) {
390 /* all workers have finished, wake the controller */
391 futex_wake(&this->parmap.thread_counter, std::numeric_limits<int>::max());
395 template <typename T> void Parmap<T>::FutexSynchro::worker_wait(unsigned round)
397 unsigned work_round = __atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST);
398 /* wait for more work */
399 while (work_round != round) {
400 futex_wait(&this->parmap.work_round, work_round);
401 work_round = __atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST);
406 template <typename T> void Parmap<T>::BusyWaitSynchro::master_signal()
408 __atomic_store_n(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
409 __atomic_add_fetch(&this->parmap.work_round, 1, __ATOMIC_SEQ_CST);
412 template <typename T> void Parmap<T>::BusyWaitSynchro::master_wait()
414 while (__atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST) < this->parmap.num_workers) {
415 std::this_thread::yield();
419 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_signal()
421 __atomic_add_fetch(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
424 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_wait(unsigned round)
426 /* wait for more work */
427 while (__atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST) != round) {
428 std::this_thread::yield();