KASKADE 7 development version
Loading...
Searching...
No Matches
threading.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2012-2025 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef THREADING_HH
14#define THREADING_HH
15
16#include <fstream>
17#include <functional>
18#include <future>
19#include <map>
20#include <mutex>
21#include <queue>
22#include <utility>
23#include <vector>
24
25#include <boost/thread/condition_variable.hpp>
26#include <boost/thread/locks.hpp>
27#include <boost/thread/mutex.hpp>
28#include <boost/thread/thread.hpp>
29
30#include "utilities/kalloc.hh"
31#include "utilities/timing.hh"
32
33namespace Kaskade
34{
39 extern std::mutex DuneQuadratureRulesMutex;
40
45 extern boost::mutex refElementMutex;
46
47 //---------------------------------------------------------------------------
48
62 template <class Index>
63 void equalWeightRanges(std::vector<Index>& x, int n);
64
77 template <class BlockIndex, class Index>
78 Index uniformWeightRangeStart(BlockIndex i, BlockIndex n, Index m)
79 {
80 assert(i>=0 && i<=n && n>0);
81 return (i*m)/n;
82 }
83
93 template <class Index>
94 Index uniformWeightRange(Index j, Index n, Index m)
95 {
96 assert(j>=0 && j<m && n>0 && m>0);
97
98 // We're looking for i such that floor(i*m/n) <= j < floor((i+1)*m/n), i.e. index j has
99 // to be in the half-open range given by the partitioning points of the range. Now this
100 // implies i*m/n-1 <= j < (i+1)*m/n and also j*n/m-1 < i <= (j+1)*n/m. As i is integer,
101 // this implies floor(j*n/m) <= i <= floor((j+1)*n/m). Typically, n/m is small, in which
102 // case this closed interval is likely to contain just one natural number - the result.
103 Index low = (j*n)/m; // floor is implied by integer arithmetics
104 Index high = ((j+1)*n)/m; // floor is implied by integer arithmetics
105
106 if (low==high)
107 {
108 assert(uniformWeightRangeStart(low,n,m)<=j && j<uniformWeightRangeStart(low+1,n,m));
109 return low;
110 }
111
112 // The implied inequality chains above are not sharp estimates, therefore the interval
113 // [low,high] can contain several natural numbers. This is always the case if n>m, i.e., we have
114 // more ranges than entries and several ranges are empty. But it can also happen if j*n/m is
115 // just below the next integral number. Now we have to walk through all natural numbers in
116 // the interval to find the correct range. TODO: is there a direct way?
117 Index i = low;
118 while (i<high && !(uniformWeightRangeStart(i,n,m)<=j && j<uniformWeightRangeStart(i+1,n,m)))
119 ++i;
120
121 assert(uniformWeightRangeStart(i,n,m)<=j && j<uniformWeightRangeStart(i+1,n,m));
122 return i;
123 }
124
125 //---------------------------------------------------------------------------
126
133 template <class T>
135 public:
140 : runningWorkers(0)
141 {
142 }
143
150 {
151 boost::lock_guard<boost::mutex> lock(q.mutex);
152 queue = std::move(q.queue);
153 }
154
161 {
162 boost::lock_guard<boost::mutex> lock(q.mutex);
163 queue = q.queue;
164 return *this;
165 }
166
167 bool empty() const
168 {
169 // we need a lock here because someone may add / remove tasks right now
170 boost::lock_guard<boost::mutex> lock(mutex);
171 return queue.empty();
172 }
173
177 size_t size() const
178 {
179 // we need a lock here because someone may add / remove tasks right now
180 boost::lock_guard<boost::mutex> lock(mutex);
181 return queue.size();
182 }
183
187 void push_back(T&& t)
188 {
189 {
190 boost::lock_guard<boost::mutex> lock(mutex);
191 queue.push(std::move(t));
192 } // release lock before waking up consumers
193 filled.notify_one();
194 }
195
202 {
203 boost::unique_lock<boost::mutex> lock(mutex);
204
205 // Wait for data to become available.
206 while (queue.empty())
207 filled.wait(lock);
208
209 // extract and remove data. When move assignment throws an exception, the queue
210 // remains unmodified
211 T t = std::move(queue.front());
212 queue.pop();
213 return t;
214 }
215
222 int running(int n)
223 {
224 boost::lock_guard<boost::mutex> lock(mutex);
225 runningWorkers += n;
226 return runningWorkers;
227 }
228
233 int running() const
234 {
235 return runningWorkers;
236 }
237
238 private:
239 std::queue<T> queue;
240 mutable boost::mutex mutex; // has to be mutable because of empty/size
241 boost::condition_variable filled;
242 int runningWorkers; // number of worker threads running on this queue
243 };
244
245 //----------------------------------------------------------------------------
246
251 typedef std::packaged_task<void()> Task;
252
257 typedef std::future<void> Ticket;
258
259
260
261 //----------------------------------------------------------------------------
262
298 class NumaThreadPool
299 {
300 public:
317 static NumaThreadPool& instance(int maxThreads = std::numeric_limits<int>::max());
318
323
327 int nodes() const
328 {
329 return nNode;
330 }
331
338 int cpus() const
339 {
340 return nCpu;
341 }
342
347 {
348 return globalQueue.running();
349 }
350
354 int cpus(int node) const
355 {
356 return cpuByNode[node].size();
357 }
358
362 int maxCpusOnNode() const
363 {
364 return maxCpusPerNode;
365 }
366
375 bool isSequential() const
376 {
377 return sequential;
378 }
379
383
388
399 Ticket run(Task&& task);
400
412 Ticket runOnNode(int node, Task&& task);
413
417
422
426 Kalloc& allocator(int node);
427
434 void* allocate(size_t n, int node);
435
439 void deallocate(void* p, size_t n, int node);
440
444 size_t alignment(int node) const;
445
454 void reserve(size_t n, size_t k, int node);
455
459
460 private:
461
462 // private constructor to be called by instance()
463 NumaThreadPool(int maxThreads);
464 ~NumaThreadPool();
465
466 Ticket runOnQueue(ConcurrentQueue<Task>& queue, Task&& task);
467
468
469 int nCpu, nNode, maxCpusPerNode;
470 std::vector<ConcurrentQueue<Task>> nodeQueue; // task queues for passing to worker threads on nodes
471 ConcurrentQueue<Task> globalQueue;
472 boost::thread_group threads; // worker threads
473 std::vector<int> nodeByCpu; // NUMA topology info
474 std::vector<std::vector<int>> cpuByNode; // NUMA topology info
475 std::map<void*,std::pair<size_t,int>> memBlocks; // NUMA memory allocations
476 std::vector<Kalloc> nodeMemory; // NUMA memory management
477 bool sequential; // if true, execute all tasks immediately
478 };
479
480 //-----------------------------------------------------------------------------------------------------
481
501 template <class Func>
502 void parallelFor(Func const& f, int maxTasks = std::numeric_limits<int>::max())
503 {
505
506 // If tasks are to be executed sequentially, we shortcut the task pool. Less for avoiding overhead,
507 // but more for avoiding task packaging, which looses call stack info if exceptions are thrown.
508 if (pool.isSequential())
509 {
510 f(0,1);
511 return;
512 }
513
514 int nTasks = std::min(4*pool.cpus(),maxTasks);
515
516 std::vector<Ticket> tickets(nTasks);
517 for (int i=0; i<nTasks; ++i)
518 tickets[i] = pool.run(Task([i,&f,nTasks] { f(i,nTasks); }));
519
520 for (auto& ticket: tickets) // wait for the tasks to be completed
521 ticket.get(); // we use get() instead of wait() to rethrow any exceptions
522 }
523
543 template <class Func>
544 void parallelFor(size_t first, size_t last, Func const& f, size_t nTasks=std::numeric_limits<size_t>::max())
545 {
546 assert(last>=first);
548 nTasks = std::min(last-first,std::min(nTasks,size_t(pool.cpus())));
549
550 std::vector<Ticket> tickets(nTasks);
551 std::mutex mutex;
552
553 TaskTiming tt(nTasks+2);
554
555 tt.start(nTasks);
556 for (size_t i=0; i<nTasks; ++i)
557 {
558 tickets[i] = pool.run(Task([&f,&first,last,&mutex,i,&tt]
559 {
560 tt.start(i);
561 while (true)
562 {
563 std::unique_lock<std::mutex> lock(mutex);
564 size_t myPos = first;
565 ++first;
566 lock.unlock();
567
568 if (myPos>=last)
569 {
570 tt.stop(i);
571 return;
572 }
573
574 f(myPos);
575 }
576 }));
577
578 // Waking up threads appears to be quite time-consuming. If we have many threads in the pool and not so much work,
579 // the last threads are woken up when all the work has already been done. Then tasks are created without benefit.
580 // In comparison, locking on a mutex appears to be blazingly fast, so we check whether there is still work to be
581 // done, and if not, leave the loop. This should be particularly beneficial in hyperthreaded systems.
582 std::lock_guard<std::mutex> lock(mutex);
583 if (first>=last)
584 {
585 tickets.resize(i+1);
586 break;
587 }
588 }
589 tt.stop(nTasks);
590
591 tt.start(nTasks+1);
592 for (auto& ticket: tickets) // wait for the tasks to be completed
593 ticket.get(); // we use get() instead of wait() to rethrow any exceptions
594 tt.stop(nTasks+1);
595
596 std::ofstream out("timing.gnu");
597 out << tt;
598 }
599
600
616 template <class Func>
617 void parallelForNodes(Func const& f, int maxTasks = std::numeric_limits<int>::max())
618 {
620 int nTasks = std::min(pool.nodes(),maxTasks);
621 std::vector<Ticket> tickets(nTasks);
622 for (int i=0; i<nTasks; ++i)
623 tickets[i] = pool.runOnNode(i,Task([i,&f,&nTasks] { f(i,nTasks); }));
624 for (auto& ticket: tickets) // wait for the tasks to be completed
625 ticket.get(); // we use get() instead of wait() to rethrow any exceptions
626 }
627
628 //----------------------------------------------------------------------------
629
633 namespace ThreadingDetail
634 {
635 class NumaAllocatorBase
636 {
637 public:
638 NumaAllocatorBase(int node);
639
640 size_t max_size() const;
641
642 void* allocate(size_t n);
643
644 void deallocate(void* p, size_t n);
645
646 int node() const
647 {
648 return nod;
649 }
650
651 private:
652 int nod;
653 Kalloc* allocator;
654 };
655 }
659
664 template <class T>
666 {
667 public:
668 typedef T value_type;
669 typedef T* pointer;
670 typedef T const* const_pointer;
671 typedef T& reference;
672 typedef T const& const_reference;
673 typedef std::size_t size_type;
674 typedef std::ptrdiff_t difference_type;
675
676 // make sure that on copying, the target copy has its data in the same
677 // NUMA memory region as the source by default -- this improves data locality.
680 typedef std::true_type propagate_on_container_swap;
681
682 template <class U>
683 struct rebind
684 {
686 };
687
695 {
696 }
697
701 int node() const
702 {
703 return alloc.node();
704 }
705
707 {
708 return &x;
709 }
710
712 {
713 return &x;
714 }
715
717 {
718 return alloc.max_size() / sizeof(T);
719 }
720
729 pointer allocate(size_type n, void* /* hint */ = 0)
730 {
731 if (n>0)
732 return static_cast<pointer>(alloc.allocate(n*sizeof(T)));
733 else
734 return nullptr;
735 }
736
738 {
739 if (p)
740 alloc.deallocate(static_cast<void*>(p),n*sizeof(T));
741 }
742
743 template< class U, class... Args >
744 void construct(U* p, Args&&... args)
745 {
746 ::new((void*)p) U(std::forward<Args>(args)...);
747 }
748
749 template <class U>
750 void destroy(U* p)
751 {
752 p->~U();
753 }
754
760 template <class U>
761 bool operator==(NumaAllocator<U> const& other) const
762 {
763 return node()==other.node();
764 }
765
766 template <class U>
767 bool operator!=(NumaAllocator<U> const& other) const
768 {
769 return !(node() == other.node());
770 }
771
772 private:
773 ThreadingDetail::NumaAllocatorBase alloc;
774 };
775
776 //----------------------------------------------------------------------------
777
784 class Mutex
785 {
786 public:
792 Mutex() = default;
793
799 Mutex(Mutex const& m) {}
800
806 Mutex& operator=(Mutex const& m) { return *this; }
807
811 boost::mutex& get() { return mutex; }
812
813 private:
814 boost::mutex mutex;
815 };
816
817 //-------------------------------------------------------------------------------------
818
830 void runInBackground(std::function<void()>& f);
831}
832
833#endif
A concurrent fifo queue.
Definition threading.hh:134
size_t size() const
Returns the number of tasks waiting.
Definition threading.hh:177
ConcurrentQueue()
Constructs an empty queue.
Definition threading.hh:139
int running(int n)
Change the number of running worker threads.
Definition threading.hh:222
void push_back(T &&t)
Stores an element at the end of the queue.
Definition threading.hh:187
ConcurrentQueue & operator=(ConcurrentQueue const &q)
Assignment.
Definition threading.hh:160
T pop_front()
Retrieves the foremost element.
Definition threading.hh:201
ConcurrentQueue(ConcurrentQueue &&q)
Moves a queue.
Definition threading.hh:149
int running() const
Get the number of running worker threads.
Definition threading.hh:233
A simple memory manager for NUMA systems.
Definition kalloc.hh:40
boost::mutex & get()
provides access to the mutex to perform the locking.
Definition threading.hh:811
Mutex & operator=(Mutex const &m)
Assignment.
Definition threading.hh:806
Mutex(Mutex const &m)
Copy constructor.
Definition threading.hh:799
Mutex()=default
Default constructor.
void construct(U *p, Args &&... args)
Definition threading.hh:744
void deallocate(pointer p, size_type n)
Definition threading.hh:737
NumaAllocator(int node)
Construct an allocator for allocating on the given NUMA node.
Definition threading.hh:694
const_pointer address(const_reference x) const
Definition threading.hh:711
pointer address(reference x) const
Definition threading.hh:706
std::true_type propagate_on_container_copy_assignment
Definition threading.hh:678
bool operator==(NumaAllocator< U > const &other) const
comparison for equality
Definition threading.hh:761
bool operator!=(NumaAllocator< U > const &other) const
Definition threading.hh:767
std::true_type propagate_on_container_swap
Definition threading.hh:680
pointer allocate(size_type n, void *=0)
Allocates the requested amount of memory.
Definition threading.hh:729
std::true_type propagate_on_container_move_assignment
Definition threading.hh:679
size_type max_size() const
Definition threading.hh:716
std::ptrdiff_t difference_type
Definition threading.hh:674
Implementation of thread pools suitable for parallelization of (more or less) memory-bound algorithms...
Definition threading.hh:299
int runningOnGlobalQueue() const
Reports how many worker threads are running to work on the global task queue.
Definition threading.hh:346
static NumaThreadPool & instance(int maxThreads=std::numeric_limits< int >::max())
Returns a globally unique thread pool instance.
int nodes() const
Reports the number of NUMA nodes (i.e., memory interfaces/CPU sockets)
Definition threading.hh:327
size_t alignment(int node) const
Reports the alignment size of allocator at given NUMA node.
void * allocate(size_t n, int node)
Allocates memory on a specific node.
int maxCpusOnNode() const
Reports the maximal number of CPUs on one node.
Definition threading.hh:362
Ticket runOnNode(int node, Task &&task)
Schedules a task to be executed on a CPU belonging to the given NUMA node.
int cpus() const
Reports the total number of CPUs (usually a multiple of nodes).
Definition threading.hh:338
void deallocate(void *p, size_t n, int node)
frees a chunk of memory previously allocated
void reserve(size_t n, size_t k, int node)
Tells the allocator to prepare for subsequent allocation of several memory blocks of same size.
bool isSequential() const
Returns true if tasks are executed sequentially. sequential execution can be enforced by calling Numa...
Definition threading.hh:375
int cpus(int node) const
Reports the number of CPUs on the given node (usually the same for all nodes).
Definition threading.hh:354
Ticket run(Task &&task)
Schedules a task to be executed on an arbitrary CPU.
Kalloc & allocator(int node)
Returns the allocator used for the given node.
A class that gathers data on task timing and provides gnuplot visualization.
Definition timing.hh:300
void start(int task)
defines the start of given task.
void stop(int task)
defines the start of given task.
Index uniformWeightRangeStart(BlockIndex i, BlockIndex n, Index m)
Computes partitioning points of ranges for uniform weight distributions.
Definition threading.hh:78
std::packaged_task< void()> Task
Abstract interface for tasks to be scheduled for concurrent execution.
Definition threading.hh:251
void runInBackground(std::function< void()> &f)
Executes a function in a child process.
std::future< void > Ticket
Abstract waitable job ticket for submitted tasks.
Definition threading.hh:257
void parallelForNodes(Func const &f, int maxTasks=std::numeric_limits< int >::max())
A parallel for loop that executes the given functor in parallel on different NUMA nodes.
Definition threading.hh:617
void equalWeightRanges(std::vector< Index > &x, int n)
Computes partitioning points such that the sum of weights in each partition is roughly the same.
Index uniformWeightRange(Index j, Index n, Index m)
Computes the range in which an index is to be found when partitioned for uniform weights.
Definition threading.hh:94
boost::mutex refElementMutex
A global lock for the Dune::GenericReferenceElement singletons, which are not thread-safe.
void parallelFor(Func const &f, int maxTasks=std::numeric_limits< int >::max())
A parallel for loop that executes the given functor in parallel on different CPUs.
Definition threading.hh:502
std::mutex DuneQuadratureRulesMutex
A global lock for the Dune::QuadratureRules factory, which is not thread-safe as of 2015-01-01.