"vscode:/vscode.git/clone" did not exist on "716584f456b3a8507779384850f4d8b85c70add0"
openmp_wrapper.h 2.19 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2017 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
5
6
7
#ifndef LIGHTGBM_OPENMP_WRAPPER_H_
#define LIGHTGBM_OPENMP_WRAPPER_H_
#ifdef _OPENMP
8
9

#include <omp.h>
10
11
#include <LightGBM/utils/log.h>

12
#include <exception>
13
#include <memory>
14
#include <mutex>
15
#include <stdexcept>
16
17
#include <vector>

18
19
20
21
22
23
24
25
inline int OMP_NUM_THREADS() {
  int ret = 1;
#pragma omp parallel
#pragma omp master
  { ret = omp_get_num_threads(); }
  return ret;
}

26
class ThreadExceptionHelper {
Nikita Titov's avatar
Nikita Titov committed
27
 public:
28
29
  ThreadExceptionHelper() {
    ex_ptr_ = nullptr;
30
31
  }

32
  ~ThreadExceptionHelper() {
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    ReThrow();
  }
  void ReThrow() {
    if (ex_ptr_ != nullptr) {
      std::rethrow_exception(ex_ptr_);
    }
  }
  void CaptureException() {
    // only catch first exception.
    if (ex_ptr_ != nullptr) { return; }
    std::unique_lock<std::mutex> guard(lock_);
    if (ex_ptr_ != nullptr) { return; }
    ex_ptr_ = std::current_exception();
  }
Nikita Titov's avatar
Nikita Titov committed
47
48

 private:
49
50
51
52
53
54
  std::exception_ptr ex_ptr_;
  std::mutex lock_;
};

#define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper
#define OMP_LOOP_EX_BEGIN() try {
Guolin Ke's avatar
Guolin Ke committed
55
56
57
58
59
60
61
62
63
#define OMP_LOOP_EX_END()                 \
  }                                       \
  catch (std::exception & ex) {           \
    Log::Warning(ex.what());              \
    omp_except_helper.CaptureException(); \
  }                                       \
  catch (...) {                           \
    omp_except_helper.CaptureException(); \
  }
64
65
#define OMP_THROW_EX() omp_except_helper.ReThrow()

66
#else
67
68

#ifdef _MSC_VER
69
  #pragma warning(disable: 4068)  // disable unknown pragma warning
70
71
72
73
74
75
76
77
78
79
80
#endif

#ifdef __cplusplus
  extern "C" {
#endif
  /** Fall here if no OPENMP support, so just
      simulate a single thread running.
      All #pragma omp should be ignored by the compiler **/
  inline void omp_set_num_threads(int) {}
  inline int omp_get_num_threads() {return 1;}
  inline int omp_get_thread_num() {return 0;}
81
  inline int OMP_NUM_THREADS() { return 1; }
82
#ifdef __cplusplus
83
};  // extern "C"
84
85
86
87
88
89
90
#endif

#define OMP_INIT_EX()
#define OMP_LOOP_EX_BEGIN()
#define OMP_LOOP_EX_END()
#define OMP_THROW_EX()

91
92
93
94
95
#endif



#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */