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