Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Summary for mistake 69 #56

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1676,6 +1676,40 @@ You should have a good reason to specify a channel size other than one for buffe

Calling `append` isn’t always data-race-free; hence, it shouldn’t be used concurrently on a shared slice.

When multiple goroutines try to append the shared slice which has the **non-full** backing array can lead to data race:
```go
s := make([]int,0,1)

go func(){
s1 := append(s, 1) // data race
fmt.Println(s1)
}()

go func() {
s2 := append(s, 1) // data race
fmt.Println(s2)
}()

```
In the above mentioned code, the slice is created with `make([]int,0,1)`, therefore length is **smaller** than capacity and the backing array isn't full. Both goroutines try to append to the same index(index 0) of the same backing array which can lead to data race. If we want to keep the existing data and append new elements to the slice which backing array isn't full, we can use `copy`:
```go
s := make([]int, 0, 1)

go func() {
sCopy := make([]int, len(s), cap(s))
copy(sCopy, s)
s1 := append(sCopy, 1)
fmt.Println(s1)
}()

go func() {
sCopy := make([]int, len(s), cap(s))
copy(sCopy, s)
s2 := append(sCopy, 1)
fmt.Println(s2)
}()
```

[Source code :simple-github:](https://github.com/teivah/100-go-mistakes/tree/master/src/09-concurrency-practice/69-data-race-append/main.go)

### Using mutexes inaccurately with slices and maps (#70)
Expand Down