linux fifo 无锁队列,是否存在乐观的无锁FIFO队列实现?

template class LFQueue {

private:

struct LFQNode {

LFQNode( T* val ) : value(val), next(nullptr) { }

T* value;

AtomicPtr next;

char pad[CACHE_LINE_SIZE - sizeof(T*) - sizeof(AtomicPtr)];

};

char pad0[CACHE_LINE_SIZE];

LFQNode* first; // for one consumer at a time

char pad1[CACHE_LINE_SIZE - sizeof(LFQNode*)];

InterlockedFlag consumerLock; // shared among consumers

char pad2[CACHE_LINE_SIZE - sizeof(InterlockedFlag)];

LFQNode* last; // for one producer at a time

char pad3[CACHE_LINE_SIZE - sizeof(LFQNode*)];

InterlockedFlag producerLock; // shared among producers

char pad4[CACHE_LINE_SIZE - sizeof(InterlockedFlag)];

public:

LFQueue() {

first = last = new LFQNode( nullptr ); // no more divider

producerLock = consumerLock = false;

}

~LFQueue() {

while( first != nullptr ) {

LFQNode* tmp = first;

first = tmp->next;

delete tmp;

}

}

bool pop( T& result ) {

while( consumerLock.set(true) )

{ } // acquire exclusivity

if( first->next != nullptr ) { // if queue is nonempty

LFQNode* oldFirst = first;

first = first->next;

T* value = first->value; // take it out

first->value = nullptr; // of the Node

consumerLock = false; // release exclusivity

result = *value; // now copy it back

delete value; // and clean up

delete oldFirst; // both allocations

return true; // and report success

}

consumerLock = false; // release exclusivity

return false; // queue was empty

}

bool push( const T& t ) {

LFQNode* tmp = new LFQNode( t ); // do work off to the side

while( producerLock.set(true) )

{ } // acquire exclusivity

last->next = tmp; // A: publish the new item

last = tmp; // B: not "last->next"

producerLock = false; // release exclusivity

return true;

}

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值