Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Typo.
[simgrid.git] / src / include / xbt / parmap.hpp
1 /* A thread pool (C++ version).                                             */
2
3 /* Copyright (c) 2004-2019 The SimGrid Team. All rights reserved.           */
4
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. */
7
8 #ifndef XBT_PARMAP_HPP
9 #define XBT_PARMAP_HPP
10
11 #include "src/internal_config.h" // HAVE_FUTEX_H
12 #include "src/kernel/context/Context.hpp"
13
14 #include <boost/optional.hpp>
15 #include <condition_variable>
16 #include <mutex>
17 #include <thread>
18
19 #if HAVE_FUTEX_H
20 #include <linux/futex.h>
21 #include <sys/syscall.h>
22 #endif
23
24 #if HAVE_PTHREAD_NP_H
25 #include <pthread_np.h>
26 #endif
27
28 XBT_LOG_EXTERNAL_CATEGORY(xbt_parmap);
29
30 namespace simgrid {
31 namespace xbt {
32
33 /** @addtogroup XBT_parmap
34  * @ingroup XBT_misc
35  * @brief Parallel map class
36  * @{
37  */
38 template <typename T> class Parmap {
39 public:
40   Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode);
41   Parmap(const Parmap&) = delete;
42   Parmap& operator=(const Parmap&) = delete;
43   ~Parmap();
44   void apply(void (*fun)(T), const std::vector<T>& data);
45   boost::optional<T> next();
46
47 private:
48   enum Flag { PARMAP_WORK, PARMAP_DESTROY };
49
50   /**
51    * @brief Thread data transmission structure
52    */
53   class ThreadData {
54   public:
55     ThreadData(Parmap<T>& parmap, int id) : parmap(parmap), worker_id(id) {}
56     Parmap<T>& parmap;
57     int worker_id;
58   };
59
60   /**
61    * @brief Synchronization object (different specializations).
62    */
63   class Synchro {
64   public:
65     explicit Synchro(Parmap<T>& parmap) : parmap(parmap) {}
66     virtual ~Synchro() = default;
67     /**
68      * @brief Wakes all workers and waits for them to finish the tasks.
69      *
70      * This function is called by the controller thread.
71      */
72     virtual void master_signal() = 0;
73     /**
74      * @brief Starts the parmap: waits for all workers to be ready and returns.
75      *
76      * This function is called by the controller thread.
77      */
78     virtual void master_wait() = 0;
79     /**
80      * @brief Ends the parmap: wakes the controller thread when all workers terminate.
81      *
82      * This function is called by all worker threads when they end (not including the controller).
83      */
84     virtual void worker_signal() = 0;
85     /**
86      * @brief Waits for some work to process.
87      *
88      * This function is called by each worker thread (not including the controller) when it has no more work to do.
89      *
90      * @param round  the expected round number
91      */
92     virtual void worker_wait(unsigned) = 0;
93
94     Parmap<T>& parmap;
95   };
96
97   class PosixSynchro : public Synchro {
98   public:
99     explicit PosixSynchro(Parmap<T>& parmap);
100     ~PosixSynchro();
101     void master_signal();
102     void master_wait();
103     void worker_signal();
104     void worker_wait(unsigned round);
105
106   private:
107     std::condition_variable ready_cond;
108     std::mutex ready_mutex;
109     std::condition_variable done_cond;
110     std::mutex done_mutex;
111   };
112
113 #if HAVE_FUTEX_H
114   class FutexSynchro : public Synchro {
115   public:
116     explicit FutexSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
117     void master_signal();
118     void master_wait();
119     void worker_signal();
120     void worker_wait(unsigned);
121
122   private:
123     static void futex_wait(unsigned* uaddr, unsigned val);
124     static void futex_wake(unsigned* uaddr, unsigned val);
125   };
126 #endif
127
128   class BusyWaitSynchro : public Synchro {
129   public:
130     explicit BusyWaitSynchro(Parmap<T>& parmap) : Synchro(parmap) {}
131     void master_signal();
132     void master_wait();
133     void worker_signal();
134     void worker_wait(unsigned);
135   };
136
137   static void* worker_main(void* arg);
138   Synchro* new_synchro(e_xbt_parmap_mode_t mode);
139   void work();
140
141   Flag status;              /**< is the parmap active or being destroyed? */
142   unsigned work_round;      /**< index of the current round */
143   std::vector<std::thread*> workers; /**< worker thread handlers */
144   unsigned num_workers;     /**< total number of worker threads including the controller */
145   Synchro* synchro;         /**< synchronization object */
146
147   unsigned thread_counter    = 0;       /**< number of workers that have done the work */
148   void (*fun)(const T)       = nullptr; /**< function to run in parallel on each element of data */
149   const std::vector<T>* data = nullptr; /**< parameters to pass to fun in parallel */
150   std::atomic<unsigned> index;          /**< index of the next element of data to pick */
151 };
152
153 /**
154  * @brief Creates a parallel map object
155  * @param num_workers number of worker threads to create
156  * @param mode how to synchronize the worker threads
157  */
158 template <typename T> Parmap<T>::Parmap(unsigned num_workers, e_xbt_parmap_mode_t mode)
159 {
160   XBT_CDEBUG(xbt_parmap, "Create new parmap (%u workers)", num_workers);
161
162   /* Initialize the thread pool data structure */
163   this->status      = PARMAP_WORK;
164   this->work_round  = 0;
165   this->workers.resize(num_workers);
166   this->num_workers = num_workers;
167   this->synchro     = new_synchro(mode);
168
169   /* Create the pool of worker threads (the caller of apply() will be worker[0]) */
170   this->workers[0] = nullptr;
171   XBT_ATTRIB_UNUSED unsigned int core_bind = 0;
172
173   for (unsigned i = 1; i < num_workers; i++) {
174     this->workers[i] = new std::thread(worker_main, new ThreadData(*this, i));
175
176     /* Bind the worker to a core if possible */
177 #if HAVE_PTHREAD_SETAFFINITY
178 #if HAVE_PTHREAD_NP_H /* FreeBSD ? */
179     cpuset_t cpuset;
180     size_t size = sizeof(cpuset_t);
181 #else /* Linux ? */
182     cpu_set_t cpuset;
183     size_t size = sizeof(cpu_set_t);
184 #endif
185     pthread_t pthread = this->workers[i]->native_handle();
186     CPU_ZERO(&cpuset);
187     CPU_SET(core_bind, &cpuset);
188     pthread_setaffinity_np(pthread, size, &cpuset);
189     if (core_bind != std::thread::hardware_concurrency() - 1)
190       core_bind++;
191     else
192       core_bind = 0;
193 #endif
194   }
195 }
196
197 /**
198  * @brief Destroys a parmap
199  */
200 template <typename T> Parmap<T>::~Parmap()
201 {
202   status = PARMAP_DESTROY;
203   synchro->master_signal();
204
205   for (unsigned i = 1; i < num_workers; i++)
206     workers[i]->join();
207
208   delete synchro;
209 }
210
211 /**
212  * @brief Applies a list of tasks in parallel.
213  * @param fun the function to call in parallel
214  * @param data each element of this vector will be passed as an argument to fun
215  */
216 template <typename T> void Parmap<T>::apply(void (*fun)(T), const std::vector<T>& data)
217 {
218   /* Assign resources to worker threads (we are maestro here)*/
219   this->fun   = fun;
220   this->data  = &data;
221   this->index = 0;
222   this->synchro->master_signal(); // maestro runs futex_wake to wake all the minions (the working threads)
223   this->work();                   // maestro works with its minions
224   this->synchro->master_wait();   // When there is no more work to do, then maestro waits for the last minion to stop
225   XBT_CDEBUG(xbt_parmap, "Job done"); //   ... and proceeds
226 }
227
228 /**
229  * @brief Returns a next task to process.
230  *
231  * Worker threads call this function to get more work.
232  *
233  * @return the next task to process, or throws a std::out_of_range exception if there is no more work
234  */
235 template <typename T> boost::optional<T> Parmap<T>::next()
236 {
237   unsigned index = this->index.fetch_add(1, std::memory_order_relaxed);
238   if (index < this->data->size())
239     return (*this->data)[index];
240   else
241     return boost::none;
242 }
243
244 /**
245  * @brief Main work loop: applies fun to elements in turn.
246  */
247 template <typename T> void Parmap<T>::work()
248 {
249   unsigned length = this->data->size();
250   unsigned index  = this->index.fetch_add(1, std::memory_order_relaxed);
251   while (index < length) {
252     this->fun((*this->data)[index]);
253     index = this->index.fetch_add(1, std::memory_order_relaxed);
254   }
255 }
256
257 /**
258  * Get a synchronization object for given mode.
259  * @param mode the synchronization mode
260  */
261 template <typename T> typename Parmap<T>::Synchro* Parmap<T>::new_synchro(e_xbt_parmap_mode_t mode)
262 {
263   if (mode == XBT_PARMAP_DEFAULT) {
264 #if HAVE_FUTEX_H
265     mode = XBT_PARMAP_FUTEX;
266 #else
267     mode = XBT_PARMAP_POSIX;
268 #endif
269   }
270   Synchro* res;
271   switch (mode) {
272     case XBT_PARMAP_POSIX:
273       res = new PosixSynchro(*this);
274       break;
275     case XBT_PARMAP_FUTEX:
276 #if HAVE_FUTEX_H
277       res = new FutexSynchro(*this);
278 #else
279       xbt_die("Futex is not available on this OS.");
280 #endif
281       break;
282     case XBT_PARMAP_BUSY_WAIT:
283       res = new BusyWaitSynchro(*this);
284       break;
285     default:
286       THROW_IMPOSSIBLE;
287   }
288   return res;
289 }
290
291 /** @brief Main function of a worker thread */
292 template <typename T> void* Parmap<T>::worker_main(void* arg)
293 {
294   ThreadData* data      = static_cast<ThreadData*>(arg);
295   Parmap<T>& parmap     = data->parmap;
296   unsigned round        = 0;
297   smx_context_t context = SIMIX_context_new(std::function<void()>(), nullptr, nullptr);
298   kernel::context::Context::set_current(context);
299
300   XBT_CDEBUG(xbt_parmap, "New worker thread created");
301
302   /* Worker's main loop */
303   while (1) {
304     round++; // New scheduling round
305     parmap.synchro->worker_wait(round);
306     if (parmap.status == PARMAP_DESTROY)
307       break;
308
309     XBT_CDEBUG(xbt_parmap, "Worker %d got a job", data->worker_id);
310     parmap.work();
311     parmap.synchro->worker_signal();
312     XBT_CDEBUG(xbt_parmap, "Worker %d has finished", data->worker_id);
313   }
314   /* We are destroying the parmap */
315   delete context;
316   delete data;
317   return nullptr;
318 }
319
320 template <typename T> Parmap<T>::PosixSynchro::PosixSynchro(Parmap<T>& parmap) : Synchro(parmap)
321 {
322 }
323
324 template <typename T> Parmap<T>::PosixSynchro::~PosixSynchro()
325 {
326 }
327
328 template <typename T> void Parmap<T>::PosixSynchro::master_signal()
329 {
330   std::unique_lock<std::mutex> lk(ready_mutex);
331   this->parmap.thread_counter = 1;
332   this->parmap.work_round++;
333   /* wake all workers */
334   ready_cond.notify_all();
335 }
336
337 template <typename T> void Parmap<T>::PosixSynchro::master_wait()
338 {
339   std::unique_lock<std::mutex> lk(done_mutex);
340   while (this->parmap.thread_counter < this->parmap.num_workers) {
341     /* wait for all workers to be ready */
342     done_cond.wait(lk);
343   }
344 }
345
346 template <typename T> void Parmap<T>::PosixSynchro::worker_signal()
347 {
348   std::unique_lock<std::mutex> lk(done_mutex);
349   this->parmap.thread_counter++;
350   if (this->parmap.thread_counter == this->parmap.num_workers) {
351     /* all workers have finished, wake the controller */
352     done_cond.notify_one();
353   }
354 }
355
356 template <typename T> void Parmap<T>::PosixSynchro::worker_wait(unsigned round)
357 {
358   std::unique_lock<std::mutex> lk(ready_mutex);
359   /* wait for more work */
360   while (this->parmap.work_round != round) {
361     ready_cond.wait(lk);
362   }
363 }
364
365 #if HAVE_FUTEX_H
366 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wait(unsigned* uaddr, unsigned val)
367 {
368   XBT_CVERB(xbt_parmap, "Waiting on futex %p", uaddr);
369   syscall(SYS_futex, uaddr, FUTEX_WAIT_PRIVATE, val, nullptr, nullptr, 0);
370 }
371
372 template <typename T> inline void Parmap<T>::FutexSynchro::futex_wake(unsigned* uaddr, unsigned val)
373 {
374   XBT_CVERB(xbt_parmap, "Waking futex %p", uaddr);
375   syscall(SYS_futex, uaddr, FUTEX_WAKE_PRIVATE, val, nullptr, nullptr, 0);
376 }
377
378 template <typename T> void Parmap<T>::FutexSynchro::master_signal()
379 {
380   __atomic_store_n(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
381   __atomic_add_fetch(&this->parmap.work_round, 1, __ATOMIC_SEQ_CST);
382   /* wake all workers */
383   futex_wake(&this->parmap.work_round, std::numeric_limits<int>::max());
384 }
385
386 template <typename T> void Parmap<T>::FutexSynchro::master_wait()
387 {
388   unsigned count = __atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST);
389   while (count < this->parmap.num_workers) {
390     /* wait for all workers to be ready */
391     futex_wait(&this->parmap.thread_counter, count);
392     count = __atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST);
393   }
394 }
395
396 template <typename T> void Parmap<T>::FutexSynchro::worker_signal()
397 {
398   unsigned count = __atomic_add_fetch(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
399   if (count == this->parmap.num_workers) {
400     /* all workers have finished, wake the controller */
401     futex_wake(&this->parmap.thread_counter, std::numeric_limits<int>::max());
402   }
403 }
404
405 template <typename T> void Parmap<T>::FutexSynchro::worker_wait(unsigned round)
406 {
407   unsigned work_round = __atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST);
408   /* wait for more work */
409   while (work_round != round) {
410     futex_wait(&this->parmap.work_round, work_round);
411     work_round = __atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST);
412   }
413 }
414 #endif
415
416 template <typename T> void Parmap<T>::BusyWaitSynchro::master_signal()
417 {
418   __atomic_store_n(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
419   __atomic_add_fetch(&this->parmap.work_round, 1, __ATOMIC_SEQ_CST);
420 }
421
422 template <typename T> void Parmap<T>::BusyWaitSynchro::master_wait()
423 {
424   while (__atomic_load_n(&this->parmap.thread_counter, __ATOMIC_SEQ_CST) < this->parmap.num_workers) {
425     std::this_thread::yield();
426   }
427 }
428
429 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_signal()
430 {
431   __atomic_add_fetch(&this->parmap.thread_counter, 1, __ATOMIC_SEQ_CST);
432 }
433
434 template <typename T> void Parmap<T>::BusyWaitSynchro::worker_wait(unsigned round)
435 {
436   /* wait for more work */
437   while (__atomic_load_n(&this->parmap.work_round, __ATOMIC_SEQ_CST) != round) {
438     std::this_thread::yield();
439   }
440 }
441
442 /** @} */
443 }
444 }
445
446 #endif