github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/3rd_party/fflib/include/ff/functionflow/utilities/simo_queue.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_SIMO_QUEUE_H_ 25 #define FF_RUNTIME_SIMO_QUEUE_H_ 26 27 #include "ff/functionflow/common/common.h" 28 namespace ff { 29 namespace rt { 30 // N, 2^N 31 //! This queue is for single-thread's push, and multiple-threads' pop. 32 //! This queue is capability-fixed 33 template <class T, size_t N> 34 class simo_queue { 35 const static int64_t MASK = (1 << N) - 1; 36 37 public: 38 simo_queue() : array(nullptr), cap(0), head(0), tail(0) { 39 array = new T[1 << N]; 40 cap = 1 << N; 41 } 42 43 bool push(const T& val) { 44 if (head - tail >= MASK) return false; 45 array[head & MASK] = val; 46 head++; 47 return true; 48 } 49 bool pop(T& val) { 50 auto t = tail; 51 if (t == head) return false; 52 val = array[t & MASK]; 53 while (!__sync_bool_compare_and_swap(&tail, t, t + 1)) { 54 t = tail; 55 if (t == head) return false; 56 val = array[t & MASK]; 57 } 58 return true; 59 } 60 size_t size() const { return head - tail; } 61 62 protected: 63 T* array; 64 int64_t cap; 65 int64_t head; 66 int64_t tail; 67 }; // end class simo_queue; 68 } 69 } // end namespace ff 70 #endif