SPSCQueue是用C++11编写的单个生产者单一消费者等待和无锁定大小队列。
示例代码SPSCQueue<int>q(2);autot=std::thread([&]{while(!q.front());std::cout<<*q.front()<<std::endl;q.pop();});q.push(1);t.join();使用SPSCQueue<T>(size_tcapacity);
Createa SPSCqueue holdingitemsoftype T withcapacity capacity.Capacityneedtobegreaterthan2.
voidemplace(Args&&...args);
Enqueueanitemusinginplaceconstruction.Blocksifqueueisfull.
booltry_emplace(Args&&...args);
Trytoenqueueanitemusinginplaceconstruction.Returns true onsuccessand false ifqueueisfull.
voidpush(constT&v);
Enqueueanitemusingcopyconstruction.Blocksifqueueisfull.
template<typenameP>voidpush(P&&v);
Enqueueanitemusingmoveconstruction.Participatesinoverloadresolutiononlyif std::is_constructible<T,P&&>::value==true.Blocksifqueueisfull.
booltry_push(constT&v);
Trytoenqueueanitemusingcopyconstruction.Returns true onsuccessand false ifqueueisfull.
template<typenameP>voidtry_push(P&&v);
Trytoenqueueanitemusingmoveconstruction.Returns true onsuccessand false ifqueueisfull.Participatesinoverloadresolutiononlyif std::is_constructible<T,P&&>::value==true.
T*front();
Returnpointertofrontofqueue.Returns nullptr ifqueueisempty.
pop();
Dequeuefirstelmentofqueue.Invalidtocallifqueueisempty.Requires std::is_nothrow_destructible<T>::value==true.
一旦一个单一的写线程可以执行入队列的操作时,只有一个单一的读线程可以执行取队列操作,其他的使用都是不允许的。
实现原理底层实现是一个环形缓冲区。
参考资料:
Intel. AvoidingandIdentifyingFalseSharingAmongThreads.Wikipedia. Ringbuffer.Wikipedia. Falsesharing.性能测试以下测试结果是基于 2socketmachinewith2xIntel(R)Xeon(R)CPUE5-26200@2.00GHz.
NUMANode/Core/Hyper-ThreadThroughput(ops/ms)LatencyRTT(ns)#0,#0,#0�,#0,#16394260#0,#0,#0�,#1,#037739238#0,#0,#0,#0,#0
评论