threading.h 1.24 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
Guolin Ke's avatar
Guolin Ke committed
5
6
7
#ifndef LIGHTGBM_UTILS_THREADING_H_
#define LIGHTGBM_UTILS_THREADING_H_

8
#include <LightGBM/utils/openmp_wrapper.h>
Guolin Ke's avatar
Guolin Ke committed
9
10

#include <functional>
11
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
12
13
14
15

namespace LightGBM {

class Threading {
Nikita Titov's avatar
Nikita Titov committed
16
 public:
Guolin Ke's avatar
Guolin Ke committed
17
18
19
20
21
22
23
24
25
26
  template<typename INDEX_T>
  static inline void For(INDEX_T start, INDEX_T end, const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) {
    int num_threads = 1;
    #pragma omp parallel
    #pragma omp master
    {
      num_threads = omp_get_num_threads();
    }
    INDEX_T num_inner = (end - start + num_threads - 1) / num_threads;
    if (num_inner <= 0) { num_inner = 1; }
27
    OMP_INIT_EX();
28
    #pragma omp parallel for schedule(static, 1)
Guolin Ke's avatar
Guolin Ke committed
29
    for (int i = 0; i < num_threads; ++i) {
30
      OMP_LOOP_EX_BEGIN();
Guolin Ke's avatar
Guolin Ke committed
31
32
33
34
35
36
      INDEX_T inner_start = start + num_inner * i;
      INDEX_T inner_end = inner_start + num_inner;
      if (inner_end > end) { inner_end = end; }
      if (inner_start < end) {
        inner_fun(i, inner_start, inner_end);
      }
37
      OMP_LOOP_EX_END();
Guolin Ke's avatar
Guolin Ke committed
38
    }
39
    OMP_THROW_EX();
Guolin Ke's avatar
Guolin Ke committed
40
41
42
43
44
  }
};

}   // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
45
#endif   // LightGBM_UTILS_THREADING_H_