単純なポインターインクリメントアロケーターの場合 (正式な名前はありますか?) ロックフリーのアルゴリズムを探しています。些細なことのように思えますが、私の実装が正しいかどうかについてのフィードバックが欲しいです。
非スレッドセーフ実装:
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 の間に割り当てを行うと、ループが再試行されます。コメントはありますか?