PolyFEM
Loading...
Searching...
No Matches
par_for.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <functional>
5#include <limits>
6#include <thread>
7
8#include <Eigen/Core>
9
10#if defined(POLYFEM_WITH_TBB) || defined(POLYFEM_WITH_CPP_THREADS)
11#include <tbb/global_control.h>
12#endif
13
14namespace polyfem
15{
16 namespace utils
17 {
20 {
21 public:
22 explicit ScopedThreadLimit(const size_t limit) : previous_(limit_)
23 {
24 limit_ = std::min(limit_, std::max(size_t(1), limit));
25 }
29 static size_t current() { return limit_; }
30
31 private:
32 inline static thread_local size_t limit_ = std::numeric_limits<size_t>::max();
33 size_t previous_;
34 };
35
36 class NThread
37 {
38 public:
39 static NThread &get()
40 {
41 static NThread instance;
42 return instance;
43 }
44
45 inline size_t num_threads() const { return num_threads_; }
46
47 void set_num_threads(const int max_threads)
48 {
49 const unsigned int tmp = max_threads <= 0 ? std::numeric_limits<int>::max() : max_threads;
50 const unsigned int num_threads = std::min(tmp, std::thread::hardware_concurrency());
51
53#if defined(POLYFEM_WITH_TBB) || defined(POLYFEM_WITH_CPP_THREADS)
54 thread_limiter = std::make_shared<tbb::global_control>(tbb::global_control::max_allowed_parallelism, num_threads);
55#endif
56 Eigen::setNbThreads(num_threads);
57 }
58
59 private:
61
62 size_t num_threads_ = 1;
63
64#if defined(POLYFEM_WITH_TBB) || defined(POLYFEM_WITH_CPP_THREADS)
66 std::shared_ptr<tbb::global_control> thread_limiter;
67#endif
68 };
69
70 void par_for(const int size, const std::function<void(int, int, int)> &func);
71 inline size_t get_n_threads() { return std::min(NThread::get().num_threads(), ScopedThreadLimit::current()); }
72 } // namespace utils
73} // namespace polyfem
static NThread & get()
Definition par_for.hpp:39
size_t num_threads() const
Definition par_for.hpp:45
void set_num_threads(const int max_threads)
Definition par_for.hpp:47
Restrict parallel work on the current thread and its CPP worker calls.
Definition par_for.hpp:20
ScopedThreadLimit(const size_t limit)
Definition par_for.hpp:22
ScopedThreadLimit & operator=(const ScopedThreadLimit &)=delete
ScopedThreadLimit(const ScopedThreadLimit &)=delete
static thread_local size_t limit_
Definition par_for.hpp:32
void par_for(const int size, const std::function< void(int, int, int)> &func)
Definition par_for.cpp:10
size_t get_n_threads()
Definition par_for.hpp:71