default_num_threads.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2021 Jérémie Dumas <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "default_num_threads.h"
  9. #include <cstdlib>
  10. #include <thread>
  11. IGL_INLINE unsigned int igl::default_num_threads(unsigned int user_num_threads) {
  12. // Thread-safe initialization using Meyers' singleton
  13. class MySingleton {
  14. public:
  15. static MySingleton &instance(unsigned int force_num_threads) {
  16. static MySingleton instance(force_num_threads);
  17. return instance;
  18. }
  19. unsigned int get_num_threads() const { return m_num_threads; }
  20. private:
  21. static const char* getenv_nowarning(const char* env_var)
  22. {
  23. #ifdef _MSC_VER
  24. #pragma warning(push)
  25. #pragma warning(disable : 4996)
  26. #endif
  27. return std::getenv(env_var);
  28. #ifdef _MSC_VER
  29. #pragma warning(pop)
  30. #endif
  31. }
  32. MySingleton(unsigned int force_num_threads) {
  33. // User-defined default
  34. if (force_num_threads) {
  35. m_num_threads = force_num_threads;
  36. return;
  37. }
  38. // Set from env var
  39. if (const char *env_str = getenv_nowarning("IGL_NUM_THREADS")) {
  40. const int env_num_thread = atoi(env_str);
  41. if (env_num_thread > 0) {
  42. m_num_threads = static_cast<unsigned int>(env_num_thread);
  43. return;
  44. }
  45. }
  46. // Guess from hardware
  47. const unsigned int hw_num_threads = std::thread::hardware_concurrency();
  48. if (hw_num_threads) {
  49. m_num_threads = hw_num_threads;
  50. return;
  51. }
  52. // Fallback when std::thread::hardware_concurrency doesn't work
  53. m_num_threads = 8u;
  54. }
  55. unsigned int m_num_threads = 0;
  56. };
  57. return MySingleton::instance(user_num_threads).get_num_threads();
  58. }