On Mon, Mar 9, 2020 at 4:16 PM Yuu LongXue <longxue...@gmail.com> wrote: > > Hi all, > > Slice is not thread safe for write operation if without lock, this is true > and I know this feature. but recently, I got a panic which caused by writing > a slice concurrently with out lock occasionally and I can't figure out why. > > ### the process as below: > 1. define a slice: var x []string > 2. append to x concurrently without lock in multi goroutines > 3. wait all goroutines to be done > 4. iterate the x slice, panic occurred when read some element with index > <strong>i (i > 0 && i < len(x)-1)</strong> in the x > > ### the question is: > In this case, the element with index 0 and index len(x) - 1 is ok to read, > but it exists a <strong>x[i](i > 0 && i < len(x)-1)</strong> that can't be > read and it will lead to panic[invalid memory address or nil pointer > dereference];
Slice is a multi word value. So writing it concurrently is not atomic and it may eventually produce a value that's a mix of the concurrently written values. After append it may happen that the slice's pointer to the backing array points incorrectly to the old value but the len and capacity are for the new value. Then it may happen that one can index only to a certain extent, lower than would be using a non corrupted slice value. Exact failure modes can be only guessed without more info. -- 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/CAA40n-VugaNa98ZCeBnWsB_W2GwgWAXCwRdjOn-LtLz%2BAOn8_w%40mail.gmail.com.