"vscode:/vscode.git/clone" did not exist on "3500cb67b90c2987202efe2bb4d0fd1917ec99b0"
openmp_wrapper.h 2.2 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
10
#include <LightGBM/utils/log.h>

Nikita Titov's avatar
Nikita Titov committed
11
12
#include <omp.h>

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

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

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

33
  ~ThreadExceptionHelper() {
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    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
48
49

 private:
50
51
52
53
54
55
  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
56
57
58
59
60
61
62
63
64
#define OMP_LOOP_EX_END()                 \
  }                                       \
  catch (std::exception & ex) {           \
    Log::Warning(ex.what());              \
    omp_except_helper.CaptureException(); \
  }                                       \
  catch (...) {                           \
    omp_except_helper.CaptureException(); \
  }
65
66
#define OMP_THROW_EX() omp_except_helper.ReThrow()

67
#else
68
69

#ifdef _MSC_VER
70
  #pragma warning(disable : 4068)  // disable unknown pragma warning
71
72
73
74
75
76
77
78
79
80
81
#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;}
82
  inline int OMP_NUM_THREADS() { return 1; }
83
#ifdef __cplusplus
84
};  // extern "C"
85
86
87
88
89
90
91
#endif

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

92
93
94
95
96
#endif



#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */