On Thu, Mar 10, 2022 at 10:31 PM Cameron Elliott <gara...@gmail.com> wrote:
>
> Ian, thank you very much for the suggestion to use atomics.
> Unfortunately, for a standard SPSC ring buffer, I don't think it does the 
> trick.
>
>
> I am attaching a simple ring buffer program at the end.
>
> If you run 'go run -race main.go' on the example,
> a race will occur.
> The race that occurs is a write, then read to the
> same element of a slice on two different goroutines.
>
> Of course a race-detected is expected.
>
> This can be fixed by mutexing Put() and Get(),
> because through some magic, mutexs affect the tables/tags
> the race detector maintains in order to catch races.
>
> Using sync.atomic on the ring buffer indexes doesn't
> affect the race-detector state for read and writes.
>
> I spent more time investigating, it seems there are
> two ways to make a traditional ring buffer compatible
> with the race detector:
>
> 1. Use build tags to conditionally Lock/Unlock mutexes
> where you would not actually need them, in order to reset
> the race detector on the object crossing goroutines.
>
> 2. Use the pragma //go:linkname to get access to the 'runtime.race'
> functions, in order to call Enable()/Disable/ReleaseMerge/Aquire
> as sync.Pool does in order to make the race detector happy.
>
> If there are other methods, please let me know!
> Thanks for any feedback!

You are getting a warning from the race detector on your code because
your code is unsafe.  Nothing ensures that the CPU running the Get
method will see the value stored by the CPU running the Put method.

You would need to use atomic operations also for storing and
retrieving the stored values.  But then they couldn't have type
interface{}.  So I don't know if there is a perfect solution here.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcW98SeuSe2faiQs6-bQQxhKdcaaJdtN4MLLfzxjZW-F1Q%40mail.gmail.com.

Reply via email to