github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/3rd_party/fflib/include/ff/functionflow/utilities/hazard_pointer.h (about) 1 /*********************************************** 2 The MIT License (MIT) 3 4 Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com> 5 6 Permission is hereby granted, free of charge, to any person obtaining a copy 7 of this software and associated documentation files (the "Software"), to deal 8 in the Software without restriction, including without limitation the rights 9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 copies of the Software, and to permit persons to whom the Software is 11 furnished to do so, subject to the following conditions: 12 13 The above copyright notice and this permission notice shall be included in 14 all copies or substantial portions of the Software. 15 16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 THE SOFTWARE. 23 *************************************************/ 24 #ifndef FF_RUNTIME_HAZARD_POINTER_H_ 25 #define FF_RUNTIME_HAZARD_POINTER_H_ 26 #include "ff/functionflow/runtime/rtcmn.h" 27 #include <atomic> 28 #include <mutex> 29 #ifdef FUNCTION_FLOW_DEBUG 30 #include <sstream> 31 #endif 32 33 //! This hazard pointer is specifical for FF!! 34 namespace ff { 35 namespace rt { 36 template <class T> 37 class hp_owner { 38 public: 39 hp_owner() : m_oflag() { 40 #ifdef CLANG_LLVM 41 m_pPointers = new std::atomic<T *>[ff::rt::concurrency()]; 42 #else 43 std::call_once(m_oflag, [this]() { 44 m_pPointers = new std::atomic<T *>[ff::rt::concurrency()]; 45 }); 46 #endif 47 } 48 49 ~hp_owner() { delete[] m_pPointers; } 50 51 std::atomic<T *> &get_hazard_pointer() { 52 return m_pPointers[ff::rt::get_thrd_id()]; 53 } 54 55 //! return true if other thread had it. 56 bool outstanding_hazard_pointer_for(T *p) { 57 thread_local static thrd_id_t id = ff::rt::get_thrd_id(); 58 if (!p) return false; 59 for (int i = 0; i < ff::rt::concurrency(); i++) { 60 if (i == id) continue; 61 if (m_pPointers[i].load(std::memory_order_acquire) == p) return true; 62 } 63 return false; 64 } 65 #ifdef FUNCTION_FLOW_DEBUG 66 std::string str() { 67 std::stringstream ss; 68 for (int i = 0; i < ff::rt::concurrency(); ++i) { 69 ss << i << ":" << m_pPointers[i].load() << ";"; 70 } 71 return ss.str(); 72 } 73 #endif 74 protected: 75 std::once_flag m_oflag; 76 std::atomic<T *> *m_pPointers; 77 }; // end class hp_owner 78 79 } // end namespace rt 80 } // end namespace ff 81 82 #endif