对于一个简单的指针增量分配器(它们有正式名称吗?)我正在寻找一种无锁算法。这似乎微不足道,但我想得到一些反馈,我的实现是否正确。
不是线程安全的实现:
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;
}
Run Code Online (Sandbox Code Playgroud)
我对线程安全实现的尝试:
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;
}
Run Code Online (Sandbox Code Playgroud)
哪里 …