openmp_wrapper.h 1.71 KB
Newer Older
1
2
3
#ifndef LIGHTGBM_OPENMP_WRAPPER_H_
#define LIGHTGBM_OPENMP_WRAPPER_H_
#ifdef _OPENMP
4
5

#include <omp.h>
6
7
#include <LightGBM/utils/log.h>

8
#include <exception>
9
#include <memory>
10
#include <mutex>
11
#include <stdexcept>
12
13
14
#include <vector>

class ThreadExceptionHelper {
Nikita Titov's avatar
Nikita Titov committed
15
 public:
16
17
  ThreadExceptionHelper() {
    ex_ptr_ = nullptr;
18
19
  }

20
  ~ThreadExceptionHelper() {
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    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
35
36

 private:
37
38
39
40
41
42
43
44
45
46
47
  std::exception_ptr ex_ptr_;
  std::mutex lock_;
};

#define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper
#define OMP_LOOP_EX_BEGIN() try {
#define OMP_LOOP_EX_END() } \
catch(std::exception& ex) { Log::Warning(ex.what()); omp_except_helper.CaptureException(); } \
catch(...) { omp_except_helper.CaptureException();  }
#define OMP_THROW_EX() omp_except_helper.ReThrow()

48
#else
49
50

#ifdef _MSC_VER
51
  #pragma warning(disable: 4068)  // disable unknown pragma warning
52
53
54
55
56
57
58
59
60
#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) {}
Guolin Ke's avatar
Guolin Ke committed
61
  inline void omp_set_nested(int) {}
62
63
64
  inline int omp_get_num_threads() {return 1;}
  inline int omp_get_thread_num() {return 0;}
#ifdef __cplusplus
65
};  // extern "C"
66
67
68
69
70
71
72
#endif

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

73
74
75
76
77
#endif



#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */