Debian Codegraph @

src/dmlc-core/include/dmlc/common.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file common.h
4 * \brief defines some common utility function.
5 */
6 #ifndef DMLC_COMMON_H_
7 #define DMLC_COMMON_H_
8
9 #include <exception>
10 #include <mutex>
11 #include <sstream>
12 #include <string>
13 #include <utility>
14 #include <vector>
15
16 #include "./logging.h"
17
18 namespace dmlc {
19 /*!
20 * \brief Split a string by delimiter
21 * \param s String to be splitted.
22 * \param delim The delimiter.
23 * \return a splitted vector of strings.
24 */
25 inline std::vector<std::string> Split(const std::string &s, char delim) {
26 std::string item;
27 std::istringstream is(s);
28 std::vector<std::string> ret;
29 while (std::getline(is, item, delim)) {
30 ret.push_back(item);
31 }
32 return ret;
33 }
34
35 /*!
36 * \brief hash an object and combines the key with previous keys
37 */
38 template <typename T>
39 inline size_t HashCombine(size_t key, const T &value) {
40 std::hash<T> hash_func;
41 return key ^ (hash_func(value) + 0x9e3779b9 + (key << 6) + (key >> 2));
42 }
43
44 /*!
45 * \brief specialize for size_t
46 */
47 template <>
48 inline size_t HashCombine<size_t>(size_t key, const size_t &value) {
49 return key ^ (value + 0x9e3779b9 + (key << 6) + (key >> 2));
50 }
51
52 /*!
53 * \brief OMP Exception class catches, saves and rethrows exception from OMP blocks
54 */
55 class OMPException {
56 private:
57 // exception_ptr member to store the exception
58 std::exception_ptr omp_exception_;
59 // mutex to be acquired during catch to set the exception_ptr
60 std::mutex mutex_;
61
62 public:
63 /*!
64 * \brief Parallel OMP blocks should be placed within Run to save exception
65 */
66 template <typename Function, typename... Parameters>
67 void Run(Function f, Parameters... params) {
68 try {
69 f(params...);
70 } catch (dmlc::Error &ex) {
71 std::lock_guard<std::mutex> lock(mutex_);
72 if (!omp_exception_) {
73 omp_exception_ = std::current_exception();
74 }
75 } catch (std::exception &ex) {
76 std::lock_guard<std::mutex> lock(mutex_);
77 if (!omp_exception_) {
78 omp_exception_ = std::current_exception();
79 }
80 }
81 }
82
83 /*!
84 * \brief should be called from the main thread to rethrow the exception
85 */
86 void Rethrow() {
87 if (this->omp_exception_) {
88 std::rethrow_exception(this->omp_exception_);
89 }
90 }
91 };
92
93 } // namespace dmlc
94
95 #endif // DMLC_COMMON_H_