1 /* 2 ** Copyright 2018 Bloomberg Finance L.P. 3 ** 4 ** Licensed under the Apache License, Version 2.0 (the "License"); 5 ** you may not use this file except in compliance with the License. 6 ** You may obtain a copy of the License at 7 ** 8 ** http://www.apache.org/licenses/LICENSE-2.0 9 ** 10 ** Unless required by applicable law or agreed to in writing, software 11 ** distributed under the License is distributed on an "AS IS" BASIS, 12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 ** See the License for the specific language governing permissions and 14 ** limitations under the License. 15 */ 16 #ifndef BLOOMBERG_QUANTUM_TASK_ID_H 17 #define BLOOMBERG_QUANTUM_TASK_ID_H 18 19 #include <ostream> 20 #include <string> 21 #include <functional> 22 #include <thread> 23 24 namespace Bloomberg { 25 namespace quantum { 26 27 struct CoroContextTag{}; 28 struct ThreadContextTag{}; 29 30 // Fwd declarations 31 class TaskId; 32 namespace local { 33 TaskId taskId(); 34 } 35 36 class TaskId 37 { 38 friend class Task; 39 friend class IoTask; 40 friend std::ostream& operator<<(std::ostream&, const TaskId&); 41 friend TaskId local::taskId(); 42 public: 43 TaskId() = default; 44 45 //Equality operators 46 bool operator==(const TaskId&) const; 47 bool operator!=(const TaskId&) const; 48 bool operator<(const TaskId&) const; 49 bool operator>(const TaskId&) const; 50 bool operator<=(const TaskId&) const; 51 bool operator>=(const TaskId&) const; 52 53 /// @brief Produces a hash value suitable for unordered map insertions 54 /// @return A hash 55 size_t hashValue() const; 56 57 /// @brief Get the id associated with this coroutine or IO task. 58 size_t id() const; 59 60 /// @brief Get the thread id where the coroutine or IO task is executing. 61 std::thread::id threadId() const; 62 63 /// @brief Checks if this id belongs to a coroutine. 64 /// @return True is it's a coroutine. 65 bool isCoroutine() const; 66 67 protected: 68 struct ThisThreadTag{}; 69 /// @brief Create using current thread id 70 explicit TaskId(ThisThreadTag); 71 /// @brief Create a coroutine id. 72 explicit TaskId(CoroContextTag); 73 /// @brief Create an IO task id. 74 explicit TaskId(ThreadContextTag); 75 76 void assignCurrentThread(); 77 private: 78 static ssize_t generate(); 79 80 ssize_t _id{0}; //negative values reserved for coroutines 81 std::thread::id _threadId; 82 }; 83 84 std::ostream& operator<<(std::ostream&, const TaskId&); 85 86 } 87 } 88 89 #include <quantum/impl/quantum_task_id_impl.h> 90 91 namespace std { 92 93 template <> 94 struct hash<Bloomberg::quantum::TaskId> 95 { 96 size_t operator()(const Bloomberg::quantum::TaskId& rhs) const { 97 return rhs.hashValue(); 98 } 99 }; 100 101 } 102 103 #endif //BLOOMBERG_QUANTUM_TASK_ID_H 104