对于一个简单的指针增量分配器(他们有正式名称吗?)我正在寻找一种无锁算法。这似乎微不足道,但我想获得一些反馈,无论我的实施是否正确。
不是线程安全的实现:
byte * head; // current head of remaining buffer
byte * end; // end of remaining buffer
void * Alloc(size_t size)
{
if (end-head < size)
return 0; // allocation failure
void * result = head;
head += size;
return head;
}
我对线程安全实现的尝试:
void * Alloc(size_t size)
{
byte * current;
do
{
current = head;
if (end - current < size)
return 0; // allocation failure
} while (CMPXCHG(&head, current+size, current) != current));
return current;
}
whereCMPXCHG
是与参数的互锁比较交换(destination, exchangeValue, comparand)
,返回原始值
对我来说看起来不错 - 如果另一个线程在 get-current 和 cmpxchg 之间分配,则循环再次尝试。任何意见?