Here is my implementation of a lock free queue using CompareAndSwap operation.
type LockFreeQueue struct {
capacity int
list []int
top int32
numPopOps int32
}
func (lfq *LockFreeQueue) Pop() (value int, empty bool) {
for {
top := atomic.LoadInt32(&lfq.top)
if top == -1 {
return -1, true
}
if top == atomic.LoadInt32(&lfq.top) {
val := lfq.list[lfq.top]
if atomic.CompareAndSwapInt32(&lfq.top, top, top-1) {
atomic.AddInt32(&lfq.numPopOps, 1)
return val, top-1 == -1
}
}
}
}
The Pop function is working as I intend it to. Is there any improvements that I can do in the code to make it more efficient?
I have intentionally not posted the code for Push function as I think it is not needed for the context.
After thinking more about the code and some suggestions, I changed the Pop function to
func (lfq *LockFreeQueue) Pop() (value int, empty bool) {
for {
top := atomic.LoadInt32(&lfq.top)
if top == -1 {
return -1, true
}
val := lfq.list[top]
if atomic.CompareAndSwapInt32(&lfq.top, top, top-1) {
atomic.AddInt32(&lfq.numPopOps, 1)
return val, false
}
}
}