对于一个简单的指针递增分配器(官方名称为何?),我正在寻找一种无锁算法。这似乎很简单,但我想得到一些反馈,以确保我的实现是正确的。
非线程安全实现:
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;
}
这里的CMPXCHG
是带有(destination, exchangeValue, comparand)
参数的交错比较交换,返回原始值。
我认为看起来不错 - 如果另一个线程在获取当前值和cmpxchg之间进行了分配,则循环会再次尝试。有什么评论吗?