Is slice in golang thread-safe for appending

5,490 views
Skip to first unread message

xiaohai dai

unread,
Jan 19, 2017, 4:43:13 PM1/19/17
to golang-nuts
I know that map in golang is not thread-safe for writing.
However, I'm not sure slice/array is thread-safe for writing. I have searched the related posts and blogs in google, but find no unambiguous statement.

Thanks in advance! 

Krzysztof Kowalczyk

unread,
Jan 19, 2017, 5:40:22 PM1/19/17
to golang-nuts
It's not and it's easy to test:

Save as t.go:

package main
import "fmt"

func main
() {
 
var s []int
 
for i := 0; i < 100000; i++ {
 go func
(n int) {
 s
= append(s, n)
 
}(i)
 
}
 fmt
.Printf("%d\n", s[0])
}


hen `go run -race t.go` and watch race detector complain.

-- kjk

Edward Muller

unread,
Jan 19, 2017, 5:40:30 PM1/19/17
to xiaohai dai, golang-nuts
No, it is not.*

* appending can replace the underlying array, so in certain situations it can be, but that's more by accident IMO so just don't rely on that.

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Stillwell

unread,
Jan 19, 2017, 5:56:48 PM1/19/17
to golang-nuts, seaf...@gmail.com
But it returns the new slice.

Edward Muller

unread,
Jan 19, 2017, 6:04:02 PM1/19/17
to Jason Stillwell, golang-nuts, seaf...@gmail.com
Which may or may not have the same backing array.


PS: I probably should have just said 'no. slices are not "thread-safe"'.  I have complicated the issue to no benefit.

Jason Stillwell

unread,
Jan 19, 2017, 6:36:30 PM1/19/17
to Edward Muller, golang-nuts, seaf...@gmail.com
Oh I see, I was thinking of the more specific question "Is appending to slices thread-safe"

xiaohai dai

unread,
Jan 19, 2017, 9:48:53 PM1/19/17
to golang-nuts
I see!
Thanks a lot!

在 2017年1月20日星期五 UTC+8上午6:40:22,Krzysztof Kowalczyk写道:

xiaohai dai

unread,
Jan 19, 2017, 9:50:41 PM1/19/17
to golang-nuts, seaf...@gmail.com
I see!
Thank you!

在 2017年1月20日星期五 UTC+8上午6:40:30,freeformz写道:

xiaohai dai

unread,
Jan 19, 2017, 9:58:19 PM1/19/17
to golang-nuts, drag...@gmail.com, seaf...@gmail.com
Wonderful!
The example in ttps://play.golang.org/p/GsffpJc1cX is great.
Thank you

在 2017年1月20日星期五 UTC+8上午7:04:02,freeformz写道:
Reply all
Reply to author
Forward
0 new messages