This is a creation in Article, where the information may have evolved or changed.
Look at a piece of code first
ackage mainimport ( "fmt" "sync")func main() { var wg sync.WaitGroup s := make([]int, 0, 1000) for i := 0; i < 1000; i++ { v := i wg.Add(1) go func() { s = append(s, v) wg.Done() }() } wg.Wait() fmt.Printf("%v\n", len(s))}
Results
第一次:928第二次:945第三次:986……
Run a few more times and you will find that the length of the slice is not 1000, but constantly changing, why?
Because append is not concurrency-safe.
Let's take a simple example, for example, when both A and B are running append and find S[1] This location is empty, they will put their values in this position, so that their values will be overwritten, resulting in data loss.
How do you write that? The simplest way is to use a lock to put an example.
package mainimport ( "fmt" "sync")func main() { var ( wg sync.WaitGroup mutex sync.Mutex ) s := make([]int, 0, 1000) for i := 0; i < 1000; i++ { v := i wg.Add(1) go func() { mutex.Lock() s = append(s, v) mutex.Unlock() wg.Done() }() } wg.Wait() fmt.Printf("%v\n", len(s))}
Running this example will find that the length of S is always 1000.