MPMCQueue 有界多生产者多用户无锁队列开源项目

我要开发同款
匿名用户2019年05月17日
11阅读
开发技术C/C++
所属分类程序开发、常用工具包
授权协议MIT

作品详情

MPMCQueue是一个用C++11编写的有界多生产者多用户无锁队列。

示例代码MPMCQueue<int>q(10);autot1=std::thread([&]{intv;q.pop(v);std::cout<<"t1"<<v<<"\n";});autot2=std::thread([&]{intv;q.pop(v);std::cout<<"t2"<<v<<"\n";});q.push(1);q.push(2);t1.join();t2.join();使用

MPMCQueue<T>(size_tcapacity);

Constructsanew MPMCQueue holdingitemsoftype T withcapacity capacity.

voidemplace(Args&&...args);

Enqueueanitemusinginplaceconstruction.Blocksifqueueisfull.

booltry_emplace(Args&&...args);

Trytoenqueueanitemusinginplaceconstruction.Returns true onsuccessand false ifqueueisfull.

boolpush(constT&v);

Enqueueanitemusingcopyconstruction.Blocksifqueueisfull.

template<typenameP>boolpush(P&&v);

Enqueueanitemusingmoveconstruction.Participatesinoverloadresolutiononlyif std::is_nothrow_constructible<T,P&&>::value==true.Blocksifqueueisfull.

booltry_push(constT&v);

Trytoenqueueanitemusingcopyconstruction.Returns true onsuccessand false ifqueueisfull.

template<typenameP>booltry_push(P&&v);

Trytoenqueueanitemusingmoveconstruction.Participatesinoverloadresolutiononlyif std::is_nothrow_constructible<T,P&&>::value==true.Returns true onsuccessand false ifqueueisfull.

voidpop(T&v);

Dequeueanitembycopyingormovingtheiteminto v.Blocksifqueueisempty.

booltry_pop(T&v);

Trytodequeueanitembycopyingormovingtheiteminto v.Return true onsucessand false ifthequeueisempty.

所有操作都是线程安全的,除了构造和析构函数。

实际原理

Enqeue:

Acquirenextwrite ticket from head.Waitforour turn (2*(ticket/capacity))towrite slot (ticket%capacity).Set turn=turn+1 toinformthereaderswearedonewriting.

Dequeue:

Acquirenextread ticket from tail.Waitforour turn (2*(ticket/capacity)+1)toread slot (ticket%capacity).Set turn=turn+1 toinformthewriterswearedonereading.

参考资料:

DaveDice. PTLQueue:ascalablebounded-capacityMPMCqueue.DmitryVyukov. BoundedMPMCqueue.MassimilianoMeneghinetal. Performanceevaluationofinter-threadcommunicationmechanismsonmulticore/multithreadedarchitectures.OleksandrOtenko. US8607249B2:Systemandmethodforefficientconcurrentqueueimplementation.PaulE.McKenney. MemoryBarriers:aHardwareViewforSoftwareHackers.
查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论