Skip to content

Instantly share code, notes, and snippets.

@gobwas
Last active November 13, 2015 15:22
Show Gist options
  • Save gobwas/4f39796f95c645bea1ac to your computer and use it in GitHub Desktop.
Save gobwas/4f39796f95c645bea1ac to your computer and use it in GitHub Desktop.
Go slice race condition example
package main
import (
"fmt"
"time"
)
type List struct {
Items []int
}
func (l *List) Add(i int) {
l.Items = append(l.Items, i)
}
var GlobalList List
func init() {
GlobalList = List{}
for {
// get case when len != cap
GlobalList.Add(0)
if len(GlobalList.Items) < cap(GlobalList.Items) {
fmt.Println("Initialized that case:", len(GlobalList.Items), cap(GlobalList.Items))
break
}
}
}
func main() {
// create concurrent writers for "clones" of GlobalList
for i := 0; i < 2; i++ {
go func(i int) {
ticker := time.NewTicker(time.Nanosecond)
for _ = range ticker.C {
clone := GlobalList
clone.Add(i)
index := len(clone.Items) - 1
// if thing that we wrote did not match actual value @_@
if clone.Items[index] != i {
fmt.Println("add failed by race")
}
}
}(i)
}
ticker := time.NewTicker(time.Millisecond * 500)
for _ = range ticker.C {
fmt.Println(GlobalList.Items[:cap(GlobalList.Items)])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment