critique mpmc stack golang implementation.

80 views
Skip to first unread message

Adam

unread,
Dec 4, 2014, 6:35:49 PM12/4/14
to lock...@googlegroups.com
please critique my mpmc stack implementation. I am unsure about a few things. First, have I used the unsafe package correctly? Second, will this implementation suffer the ABA problem?


type Stack struct {
next unsafe.Pointer
}

type Element struct {
next  unsafe.Pointer
value int
}

func (stack *Stack) Push(value int) (b bool) {
pushed := Element{value: value}
up_pushed := unsafe.Pointer(&pushed)
for {
pushed.next = atomic.LoadPointer(&stack.next)
if atomic.CompareAndSwapPointer(&stack.next, pushed.next, up_pushed) {
b = true
return
}
}
return
}

func (stack *Stack) Pop() (b bool, value int) {
for {
up_popped := atomic.LoadPointer(&stack.next)
if up_popped == nil {
return
}
popped := *(*Element)(unsafe.Pointer(up_popped))
if atomic.CompareAndSwapPointer(&stack.next, up_popped, popped.next) {
b = true
value = popped.value
popped.next = nil
return
}

}
return
}

Dmitry Vyukov

unread,
Dec 5, 2014, 2:13:53 PM12/5/14
to lock...@googlegroups.com
Looks correct to me.
It will not suffer from ABA, because you create a new node on each
push, and then give it to GC.
While a goroutine holds a reference to A in pushed.next, GC will not
collect A, and so A cannot appear again in stack.next.
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "Scalable Synchronization Algorithms" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to lock-free+...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/lock-free/b94e7686-57e3-4cc8-9697-9e51f5085750%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Dmitry Vyukov

All about lockfree/waitfree algorithms, multicore, scalability,
parallel computing and related topics:
http://www.1024cores.net
Reply all
Reply to author
Forward
0 new messages