openmp_wrapper.h 2.01 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
18
#include <vector>

class ThreadExceptionHelper {
Nikita Titov's avatar
Nikita Titov committed
19
 public:
20
21
  ThreadExceptionHelper() {
    ex_ptr_ = nullptr;
22
23
  }

24
  ~ThreadExceptionHelper() {
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    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
39
40

 private:
41
42
43
44
45
46
  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
47
48
49
50
51
52
53
54
55
#define OMP_LOOP_EX_END()                 \
  }                                       \
  catch (std::exception & ex) {           \
    Log::Warning(ex.what());              \
    omp_except_helper.CaptureException(); \
  }                                       \
  catch (...) {                           \
    omp_except_helper.CaptureException(); \
  }
56
57
#define OMP_THROW_EX() omp_except_helper.ReThrow()

58
#else
59
60

#ifdef _MSC_VER
61
  #pragma warning(disable: 4068)  // disable unknown pragma warning
62
63
64
65
66
67
68
69
70
71
72
73
#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;}
#ifdef __cplusplus
74
};  // extern "C"
75
76
77
78
79
80
81
#endif

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

82
83
84
85
86
#endif



#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */