Repository: craflin/LockFreeQueue Branch: master Commit: 2d9f743bc797 Files: 16 Total size: 41.8 KB Directory structure: gitextract_8qognr8x/ ├── .gitmodules ├── LICENSE ├── LockFreeLifoQueue.h ├── LockFreeQueue.h ├── LockFreeQueueCpp11.h ├── LockFreeQueueSlow1.h ├── LockFreeQueueSlow2.h ├── LockFreeQueueSlow3.h ├── Marefile ├── MutexLockQueue.h ├── README.md ├── SpinLockQueue.h ├── Test.cpp ├── generate ├── generate.bat └── mpmc_bounded_queue.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitmodules ================================================ [submodule "Ext/libnstd"] path = Ext/libnstd url = https://github.com/craflin/libnstd.git [submodule "Ext/mare"] path = Ext/mare url = https://github.com/craflin/mare.git ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: LockFreeLifoQueue.h ================================================ #pragma once #include #include template class LockFreeLifoQueue { public: explicit LockFreeLifoQueue(usize capacity) : _capacity(capacity) { _indexMask = capacity; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _indexMask |= _indexMask >> i; _abaOffset = _indexMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * (capacity + 1)); for(usize i = 1; i < capacity;) { Node& node = _queue[i]; node.abaNextFree = ++i; } _queue[capacity].abaNextFree = 0; _abaFree = 1; _abaPushed = 0; } ~LockFreeLifoQueue() { for(usize abaPushed = _abaPushed;;) { usize nodeIndex = abaPushed & _indexMask; if(!nodeIndex) break; Node& node = _queue[nodeIndex]; abaPushed = node.abaNextPushed; (&node.data)->~T(); } Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const {return 0;} bool push(const T& data) { Node* node; usize abaFree; for(;;) { abaFree = _abaFree; usize nodeIndex = abaFree & _indexMask; if(!nodeIndex) return false; node = &_queue[nodeIndex]; if(Atomic::compareAndSwap(_abaFree, abaFree, node->abaNextFree + _abaOffset) == abaFree) break; } new (&node->data)T(data); for(;;) { usize abaPushed = _abaPushed; node->abaNextPushed = abaPushed; if(Atomic::compareAndSwap(_abaPushed, abaPushed, abaFree) == abaPushed) return true; } } bool pop(T& result) { Node* node; usize abaPushed; for(;;) { abaPushed = _abaPushed; usize nodeIndex = abaPushed & _indexMask; if(!nodeIndex) return false; node = &_queue[nodeIndex]; if(Atomic::compareAndSwap(_abaPushed, abaPushed, node->abaNextPushed + _abaOffset) == abaPushed) break; } result = node->data; (&node->data)->~T(); abaPushed += _abaOffset; for(;;) { usize abaFree = _abaFree; node->abaNextFree = abaFree; if(Atomic::compareAndSwap(_abaFree, abaFree, abaPushed) == abaFree) return true; } } private: struct Node { T data; volatile usize abaNextFree; volatile usize abaNextPushed; }; private: usize _indexMask; Node* _queue; usize _abaOffset; usize _capacity; char cacheLinePad1[64]; volatile usize _abaFree; char cacheLinePad2[64]; volatile usize _abaPushed; char cacheLinePad3[64]; }; ================================================ FILE: LockFreeQueue.h ================================================ #pragma once #include #include template class LockFreeQueue { public: explicit LockFreeQueue(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); for(usize i = 0; i < _capacity; ++i) { _queue[i].tail = i; _queue[i].head = -1; } _tail = 0; _head = 0; } ~LockFreeQueue() { for(usize i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const { usize head = Atomic::load(_head); return _tail - head; } bool push(const T& data) { Node* node; usize next, tail = _tail; for(;; tail = next) { node = &_queue[tail & _capacityMask]; if(Atomic::load(node->tail) != tail) return false; if((next = Atomic::compareAndSwap(_tail, tail, tail + 1)) == tail) break; } new (&node->data)T(data); Atomic::store(node->head, tail); return true; } bool pop(T& result) { Node* node; usize next, head = _head; for(;; head = next) { node = &_queue[head & _capacityMask]; if(Atomic::load(node->head) != head) return false; if((next = Atomic::compareAndSwap(_head, head, head + 1)) == head) break; } result = node->data; (&node->data)->~T(); Atomic::store(node->tail, head + _capacity); return true; } private: struct Node { T data; usize tail; usize head; }; private: usize _capacityMask; Node* _queue; usize _capacity; char cacheLinePad1[64]; usize _tail; char cacheLinePad2[64]; usize _head; char cacheLinePad3[64]; }; ================================================ FILE: LockFreeQueueCpp11.h ================================================ #pragma once #include #include template class LockFreeQueueCpp11 { public: explicit LockFreeQueueCpp11(size_t capacity) { _capacityMask = capacity - 1; for(size_t i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)new char[sizeof(Node) * _capacity]; for(size_t i = 0; i < _capacity; ++i) { _queue[i].tail.store(i, std::memory_order_relaxed); _queue[i].head.store(-1, std::memory_order_relaxed); } _tail.store(0, std::memory_order_relaxed); _head.store(0, std::memory_order_relaxed); } ~LockFreeQueueCpp11() { for(size_t i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); delete [] (char*)_queue; } size_t capacity() const {return _capacity;} size_t size() const { size_t head = _head.load(std::memory_order_acquire); return _tail.load(std::memory_order_relaxed) - head; } bool push(const T& data) { Node* node; size_t tail = _tail.load(std::memory_order_relaxed); for(;;) { node = &_queue[tail & _capacityMask]; if(node->tail.load(std::memory_order_relaxed) != tail) return false; if((_tail.compare_exchange_weak(tail, tail + 1, std::memory_order_relaxed))) break; } new (&node->data)T(data); node->head.store(tail, std::memory_order_release); return true; } bool pop(T& result) { Node* node; size_t head = _head.load(std::memory_order_relaxed); for(;;) { node = &_queue[head & _capacityMask]; if(node->head.load(std::memory_order_relaxed) != head) return false; if(_head.compare_exchange_weak(head, head + 1, std::memory_order_relaxed)) break; } result = node->data; (&node->data)->~T(); node->tail.store(head + _capacity, std::memory_order_release); return true; } private: struct Node { T data; std::atomic tail; std::atomic head; }; private: size_t _capacityMask; Node* _queue; size_t _capacity; char cacheLinePad1[64]; std::atomic _tail; char cacheLinePad2[64]; std::atomic _head; char cacheLinePad3[64]; }; ================================================ FILE: LockFreeQueueSlow1.h ================================================ #pragma once #include #include template class LockFreeQueueSlow1 { public: explicit LockFreeQueueSlow1(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); for(Node* node = _queue, * end = _queue + _capacity; node < end; ++node) node->state = Node::free; _freeNodes = _capacity; _occupiedNodes = 0; _writeIndex = -1; _safeWriteIndex = -1; _readIndex = -1; _safeReadIndex = -1; } ~LockFreeQueueSlow1() { for(Node* node = _queue, * end = _queue + _capacity; node < end; ++node) switch(node->state) { case Node::set: case Node::occupied: (&node->data)->~T(); break; default: break; } Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const {return _capacity - _freeNodes;} bool push(const T& data) { begin: usize freeNodes = _freeNodes; if(freeNodes == 0) return false; // queue is full if(Atomic::compareAndSwap(_freeNodes, freeNodes, freeNodes - 1) != freeNodes) goto begin; usize writeIndex = Atomic::increment(_writeIndex); Node* node = &_queue[writeIndex & _capacityMask]; ASSERT(node->state == Node::free); new (&node->data)T(data); Atomic::store(node->state, Node::set); commit: usize safeWriteIndex = _safeWriteIndex; usize nextSafeWriteIndex = safeWriteIndex + 1; commitNext: node = &_queue[nextSafeWriteIndex & _capacityMask]; if(node->state == Node::set && Atomic::compareAndSwap(node->state, Node::set, Node::occupied) == Node::set) { if(Atomic::compareAndSwap(_safeWriteIndex, safeWriteIndex, nextSafeWriteIndex) == safeWriteIndex) { Atomic::increment(_occupiedNodes); safeWriteIndex = nextSafeWriteIndex; ++nextSafeWriteIndex; goto commitNext; } else node->state = Node::set; goto commit; } return true; } bool pop(T& result) { begin: usize occupiedNodes = _occupiedNodes; if(occupiedNodes == 0) return false; // queue is empty if(Atomic::compareAndSwap(_occupiedNodes, occupiedNodes, occupiedNodes - 1) != occupiedNodes) goto begin; usize readIndex = Atomic::increment(_readIndex); Node* node = &_queue[readIndex & _capacityMask]; ASSERT(node->state == Node::occupied); result = node->data; (&node->data)->~T(); Atomic::store(node->state, Node::unset); release: usize safeReadIndex = _safeReadIndex; usize nextSafeReadIndex = safeReadIndex + 1; releaseNext: node = &_queue[nextSafeReadIndex & _capacityMask]; if(node->state == Node::unset && Atomic::compareAndSwap(node->state, Node::unset, Node::free) == Node::unset) { if(Atomic::compareAndSwap(_safeReadIndex, safeReadIndex, nextSafeReadIndex) == safeReadIndex) { Atomic::increment(_freeNodes); safeReadIndex = nextSafeReadIndex; ++nextSafeReadIndex; goto releaseNext; } else node->state = Node::unset; goto release; } return true; } private: struct Node { T data; enum State { free, set, occupied, unset, }; volatile int state; }; private: usize _capacityMask; Node* _queue; usize _capacity; volatile usize _freeNodes; volatile usize _occupiedNodes; volatile usize _writeIndex; volatile usize _safeWriteIndex; volatile usize _readIndex; volatile usize _safeReadIndex; }; ================================================ FILE: LockFreeQueueSlow2.h ================================================ #pragma once #include #include template class LockFreeQueueSlow2 { public: explicit LockFreeQueueSlow2(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); for(usize i = 0; i < _capacity; ++i) { _queue[i].tail = i; _queue[i].head = i - 1; } _tail = 0; _head = 0; } ~LockFreeQueueSlow2() { for(usize i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const { usize head = Atomic::load(_head); return _tail - head; } bool push(const T& data) { begin: usize tail = _tail; Node* node = &_queue[tail & _capacityMask]; usize newTail = tail + 1; usize nodeTail = node->tail; if(nodeTail == tail) { nodeTail = Atomic::compareAndSwap(node->tail, tail, newTail); if(nodeTail == tail) { Atomic::compareAndSwap(_tail, tail, newTail); new (&node->data)T(data); Atomic::store(node->head, tail); return true; } } if(nodeTail == newTail) { Atomic::compareAndSwap(_tail, tail, newTail); goto begin; } else return false; } bool pop(T& result) { begin: usize head = _head; Node* node = &_queue[head & _capacityMask]; usize newHead = head + 1; usize nodeHead = node->head; if(nodeHead == head) { nodeHead = Atomic::compareAndSwap(node->head, head, newHead); if(nodeHead == head) { Atomic::compareAndSwap(_head, head, newHead); result = node->data; (&node->data)->~T(); Atomic::store(node->tail, head + _capacity); return true; } } if(nodeHead == newHead) { Atomic::compareAndSwap(_head, head, newHead); goto begin; } else return false; } private: struct Node { T data; volatile usize head; volatile usize tail; }; private: usize _capacityMask; Node* _queue; usize _capacity; char cacheLinePad1[64]; volatile usize _head; char cacheLinePad2[64]; volatile usize _tail; char cacheLinePad3[64]; }; ================================================ FILE: LockFreeQueueSlow3.h ================================================ #pragma once #include #include template class LockFreeQueueSlow3 { public: explicit LockFreeQueueSlow3(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); for(usize i = 0; i < _capacity; ++i) _queue[i].state = 0; _tail = 0; _head = 0; } ~LockFreeQueueSlow3() { for(usize i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const { usize head = Atomic::load(_head); return _tail - head; } bool push(const T& data) { for(;;) { usize tail = _tail; Node* node = &_queue[tail & _capacityMask]; switch(Atomic::compareAndSwap(node->state, 0, 2)) { case 2: continue; case 0: break; default: return false; } if(Atomic::compareAndSwap(_tail, tail, tail + 1) == tail) { new (&node->data)T(data); Atomic::store(node->state, 1); return true; } else node->state = 0; } } bool pop(T& result) { for(;;) { usize head = _head; Node* node = &_queue[head & _capacityMask]; switch(Atomic::compareAndSwap(node->state, 1, 3)) { case 3: continue; case 1: break; default: return false; } if(Atomic::compareAndSwap(_head, head, head + 1) == head) { result = node->data; (&node->data)->~T(); Atomic::store(node->state, 0); return true; } else node->state = 1; } } private: struct Node { T data; volatile int state; }; private: usize _capacityMask; Node* _queue; usize _capacity; char cacheLinePad1[64]; volatile usize _tail; char cacheLinePad2[64]; volatile usize _head; char cacheLinePad3[64]; }; ================================================ FILE: Marefile ================================================ if(tool == "vcxproj") { platforms = { "Win32", "x64" } } buildDir = "Build/$(configuration)/.$(target)" targets = { LockFreeQueue = cppApplication + { dependencies = { "libnstd" } includePaths = { "Ext/libnstd/include" } libPaths = { "Build/$(configuration)/.libnstd" } libs = { "nstd" } root = "Src" files = { "*.cpp" = cppSource "*.h" } if tool == "vcxproj" { linkFlags += { "/SUBSYSTEM:CONSOLE" } } if platform == "Linux" { libs += { "pthread", "rt" } cppFlags += { "-std=c++11" } } defines -= "NDEBUG" } include "Ext/libnstd/libnstd.mare" libnstd += { folder = "Ext" } } ================================================ FILE: MutexLockQueue.h ================================================ #pragma once #include #include template class MutexLockQueue { public: explicit MutexLockQueue(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); _head = 0; _tail = 0; } ~MutexLockQueue() { for(usize i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const { usize result; _mutex.lock(); result = _tail - _head; _mutex.unlock(); return result; } bool push(const T& data) { _mutex.lock(); if(_tail - _head == _capacity) { _mutex.unlock(); return false; // queue is full } Node& node = _queue[(_tail++) & _capacityMask]; new (&node.data)T(data); _mutex.unlock(); return true; } bool pop(T& result) { _mutex.lock(); if(_head == _tail) { _mutex.unlock(); return false; // queue is empty } Node& node = _queue[(_head++) & _capacityMask]; result = node.data; (&node.data)->~T(); _mutex.unlock(); return true; } private: struct Node { T data; }; private: usize _capacityMask; Node* _queue; usize _capacity; usize _head; usize _tail; mutable Mutex _mutex; }; ================================================ FILE: README.md ================================================ LockFreeQueue ============= Here, I am testing some multi-producer multi-consumer bounded ring buffer FIFO queue implementations for fun. * [LockFreeQueueCpp11.h](LockFreeQueueCpp11.h) - The fastest lock free queue I have managed to implement. * [LockFreeQueue.h](LockFreeQueue.h) - The fastest lock free queue I have managed to implement without c++11. It is equally fast as LockFreeQueueCpp11.h. * [mpmc_bounded_queue.h](mpmc_bounded_queue.h) - Bounded MPMC queue by [Dmitry Vyukov, 2011] * [LockFreeQueueSlow1.h](LockFreeQueueSlow1.h) - My first attempt at implementing a lock free queue. It is working correctly, but it is a lot slower than LockFreeQueue.h. * [LockFreeQueueSlow2.h](LockFreeQueueSlow2.h) - A lock free queue based on [John D. Valois, 1994]. The queue uses Valois' algorithm adapted to a ring buffer structure with some modifications to tackle the ABA-Problem. * [LockFreeQueueSlow3.h](LockFreeQueueSlow3.h) - Another lock free queue almost as fast as LockFreeQueue.h. * [MutexLockQueue.h](MutexLockQueue.h) - A naive queue implementation that uses a conventional mutex lock (CriticalSecion / pthread-Mutex). * [SpinLockQueue.h](SpinLockQueue.h) - A naive queue implementation that uses an atomic TestAndSet-lock. And for the fun of it, here is a multi-producer multi-consumer LIFO queue: * [LockFreeLifoQueue.h](LockFreeLifoQueue.h) - A lock free multi-producer multi-consumer bounded LIFO queue. #### References [John D. Valois, 1994] - Implementing Lock-Free Queues
[Dmitry Vyukov, 2011] - [Bounded MPMC queue](http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue) ================================================ FILE: SpinLockQueue.h ================================================ #pragma once #include #include template class SpinLockQueue { public: explicit SpinLockQueue(usize capacity) { _capacityMask = capacity - 1; for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1) _capacityMask |= _capacityMask >> i; _capacity = _capacityMask + 1; _queue = (Node*)Memory::alloc(sizeof(Node) * _capacity); _lock = 0; _head = 0; _tail = 0; } ~SpinLockQueue() { for(usize i = _head; i != _tail; ++i) (&_queue[i & _capacityMask].data)->~T(); Memory::free(_queue); } usize capacity() const {return _capacity;} usize size() const { usize result; while(Atomic::testAndSet(_lock) != 0); result = _tail - _head; Atomic::store(_lock, 0); return result; } bool push(const T& data) { while(Atomic::testAndSet(_lock) != 0); if(_tail - _head == _capacity) { _lock = 0; return false; // queue is full } Node& node = _queue[(_tail++) & _capacityMask]; new (&node.data)T(data); Atomic::store(_lock, 0); return true; } bool pop(T& result) { while(Atomic::testAndSet(_lock) != 0); if(_head == _tail) { _lock = 0; return false; // queue is empty } Node& node = _queue[(_head++) & _capacityMask]; result = node.data; (&node.data)->~T(); Atomic::store(_lock, 0); return true; } private: struct Node { T data; }; private: usize _capacityMask; Node* _queue; usize _capacity; usize _head; usize _tail; mutable volatile int32 _lock; }; ================================================ FILE: Test.cpp ================================================ #include #include #include #include #include #include "LockFreeQueueCpp11.h" #include "LockFreeQueue.h" #include "LockFreeQueueSlow1.h" #include "LockFreeQueueSlow2.h" #include "LockFreeQueueSlow3.h" #include "MutexLockQueue.h" #include "SpinLockQueue.h" #include "mpmc_bounded_queue.h" #include "LockFreeLifoQueue.h" static const int testItems = 250000 * 64 / 3 * 10; static const int testThreadConsumerThreads = 8; static const int testThreadProducerThreads = 8; static const int testItemsPerConsumerThread = testItems / testThreadConsumerThreads; static const int testItemsPerProducerThread = testItems / testThreadProducerThreads; template class IQueue { public: virtual usize size() const = 0; virtual usize capacity() const = 0; virtual bool push(const T& data) = 0; virtual bool pop(T& result) = 0; }; template class TestQueue : public IQueue { public: TestQueue(usize size) : queue(size) {} usize size() const {return queue.size();} usize capacity() const {return queue.capacity();} bool push(const T& data) {return queue.push(data);} bool pop(T& result) {return queue.pop(result);} private: Q queue; }; volatile usize producerSum; volatile usize consumerSum; volatile int64 maxPushDuration; volatile int64 maxPopDuration; uint producerThread(void* param) { IQueue* queue = (IQueue*)param; for(int i = 0; i < testItemsPerProducerThread; ++i) { for(;;) { int64 startTime = Time::microTicks(); while(!queue->push(i)) { Thread::yield(); startTime = Time::microTicks(); } { int64 duration = Time::microTicks() - startTime; for(;;) { int64 lmaxPushDuration = maxPushDuration; if(duration <= lmaxPushDuration || Atomic::compareAndSwap(maxPushDuration, lmaxPushDuration, duration) == lmaxPushDuration) break; } break; } } Atomic::fetchAndAdd(producerSum, i); } return 0; } uint consumerThread(void* param) { IQueue* queue = (IQueue*)param; int val; for(int i = 0; i < testItemsPerConsumerThread; ++i) { for(;;) { int64 startTime = Time::microTicks(); while(!queue->pop(val)) { Thread::yield(); startTime = Time::microTicks(); } { int64 duration = Time::microTicks() - startTime; for(;;) { int64 lmaxPopDuration = maxPopDuration; if(duration <= lmaxPopDuration || Atomic::compareAndSwap(maxPopDuration, lmaxPopDuration, duration) == lmaxPopDuration) break; } break; } } Atomic::fetchAndAdd(consumerSum, val); } return 0; } template void testQueue(const String& name, bool fifo = false) { Console::printf(_T("Testing %s... \n"), (const tchar*)name); volatile int32 int32_ = 0; volatile uint32 uint32_ = 0; ASSERT(Atomic::compareAndSwap(int32_, 0, 1) == 0); ASSERT(int32_ == 1); ASSERT(Atomic::compareAndSwap(uint32_, 0, 1) == 0); ASSERT(uint32_ == 1); volatile int64 int64_ = 0; volatile uint64 uint64_ = 0; ASSERT(Atomic::compareAndSwap(int64_, 0, 1) == 0); ASSERT(int64_ == 1); ASSERT(Atomic::compareAndSwap(uint64_, 0, 1) == 0); ASSERT(uint64_ == 1); { TestQueue queue(10000); int result; ASSERT(queue.capacity() >= 10000); ASSERT(!queue.pop(result)); ASSERT(queue.push(42)); ASSERT(queue.pop(result)); ASSERT(result == 42); ASSERT(!queue.pop(result)); } { TestQueue queue(2); int result; ASSERT(queue.capacity() >= 2); ASSERT(!queue.pop(result)); ASSERT(queue.push(42)); ASSERT(queue.push(43)); ASSERT(queue.pop(result)); ASSERT(result == (fifo ? 43 : 42)); ASSERT(queue.pop(result)); ASSERT(result == (fifo ? 42 : 43)); ASSERT(!queue.pop(result)); ASSERT(queue.push(44)); ASSERT(queue.push(45)); ASSERT(queue.pop(result)); ASSERT(result == (fifo ? 45 : 44)); ASSERT(queue.push(47)); } producerSum = 0; consumerSum = 0; maxPushDuration = 0; maxPopDuration = 0; int64 microStartTime = Time::microTicks(); { TestQueue queue(100); List threads; for(int i = 0; i < testThreadProducerThreads; ++i) { Thread* thread = new Thread; thread->start(producerThread, &queue); threads.append(thread); } for(int i = 0; i < testThreadConsumerThreads; ++i) { Thread* thread = new Thread; thread->start(consumerThread, &queue); threads.append(thread); } for(List::Iterator i = threads.begin(), end = threads.end(); i != end; ++i) { Thread* thread = *i; thread->join(); delete thread; } ASSERT(queue.size() == 0); ASSERT(producerSum == consumerSum); } int64 microDuration = Time::microTicks() - microStartTime; Console::printf(_T("%lld ms, maxPush: %lld microseconds, maxPop: %lld microseconds\n"), microDuration / 1000, maxPushDuration, maxPopDuration); } int main(int argc, char* argv[]) { for(int i = 0; i < 3; ++i) { Console::printf(_T("--- Run %d ---\n"), i); testQueue >("LockFreeQueueCpp11"); testQueue >("mpmc_bounded_queue"); testQueue >("LockFreeQueue"); testQueue >("LockFreeQueueSlow1"); testQueue >("LockFreeQueueSlow2"); testQueue >("LockFreeQueueSlow3"); testQueue >("MutexLockQueue"); testQueue >("SpinLockQueue"); testQueue >("LockFreeLifoQueue", true); } return 0; } ================================================ FILE: generate ================================================ #!/bin/sh [ ! -f "Build/Debug/.mare/mare" ] && Ext/mare/compile --buildDir=Build/Debug/.mare --outputDir=Build/Debug/.mare --sourceDir=Ext/mare/src Build/Debug/.mare/mare $@ ================================================ FILE: generate.bat ================================================ @echo off if not exist Build\Debug\.mare\mare.exe call Ext\mare\compile.bat --buildDir=Build/Debug/.mare --outputDir=Build/Debug/.mare --sourceDir=Ext/mare/src if not "%1"=="" (Build\Debug\.mare\mare.exe %*) else Build\Debug\.mare\mare.exe --vcxproj=2013 ================================================ FILE: mpmc_bounded_queue.h ================================================ /* Multi-producer/multi-consumer bounded queue. * Copyright (c) 2010-2011, Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted * as representing official policies, either expressed or implied, of Dmitry Vyukov. */ #include #include template class mpmc_bounded_queue { private: static inline size_t nextPowerOfTwo(size_t buffer_size) { size_t result = buffer_size - 1; for(size_t i = 1; i <= sizeof(void*) * 4; i <<= 1) result |= result >> i; return result + 1; } public: mpmc_bounded_queue(size_t buffer_size) : buffer_(new cell_t [nextPowerOfTwo(buffer_size)]) , buffer_mask_(nextPowerOfTwo(buffer_size) - 1) { buffer_size = buffer_mask_ + 1; assert((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)); for (size_t i = 0; i != buffer_size; i += 1) buffer_[i].sequence_.store(i, std::memory_order_relaxed); enqueue_pos_.store(0, std::memory_order_relaxed); dequeue_pos_.store(0, std::memory_order_relaxed); } ~mpmc_bounded_queue() { delete [] buffer_; } size_t size() const { size_t head = dequeue_pos_.load(std::memory_order_acquire);; return enqueue_pos_.load(std::memory_order_relaxed) - head; } size_t capacity() const { return buffer_mask_ + 1; } bool push(T const& data) { cell_t* cell; size_t pos = enqueue_pos_.load(std::memory_order_relaxed); for (;;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = (intptr_t)seq - (intptr_t)pos; if (dif == 0) { if (enqueue_pos_.compare_exchange_weak (pos, pos + 1, std::memory_order_relaxed)) break; } else if (dif < 0) return false; else pos = enqueue_pos_.load(std::memory_order_relaxed); } cell->data_ = data; cell->sequence_.store(pos + 1, std::memory_order_release); return true; } bool pop(T& data) { cell_t* cell; size_t pos = dequeue_pos_.load(std::memory_order_relaxed); for (;;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = (intptr_t)seq - (intptr_t)(pos + 1); if (dif == 0) { if (dequeue_pos_.compare_exchange_weak (pos, pos + 1, std::memory_order_relaxed)) break; } else if (dif < 0) return false; else pos = dequeue_pos_.load(std::memory_order_relaxed); } data = cell->data_; cell->sequence_.store (pos + buffer_mask_ + 1, std::memory_order_release); return true; } private: struct cell_t { std::atomic sequence_; T data_; }; static size_t const cacheline_size = 64; typedef char cacheline_pad_t [cacheline_size]; cacheline_pad_t pad0_; cell_t* const buffer_; size_t const buffer_mask_; cacheline_pad_t pad1_; std::atomic enqueue_pos_; cacheline_pad_t pad2_; std::atomic dequeue_pos_; cacheline_pad_t pad3_; mpmc_bounded_queue(mpmc_bounded_queue const&); void operator = (mpmc_bounded_queue const&); };