Home >Backend Development >Golang >Why is `append` function not thread-safe for concurrent access in Go?

Why is `append` function not thread-safe for concurrent access in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 03:50:02389browse

Why is `append` function not thread-safe for concurrent access in Go?

Append Function: Not Thread-Safe for Concurrent Access

When utilizing goroutines concurrently to append elements to a slice within a for loop, anomalies in data can arise. Missing or blank data may appear in the resultant slice, indicating potential data races.

This occurs because in Go, no value is innately safe for simultaneous read and write. Slices, which are represented by slice headers, are no exception. The code provided exhibits data races due to concurrent access:

destSlice := make([]myClass, 0)

var wg sync.WaitGroup
for _, myObject := range sourceSlice {
    wg.Add(1)
    go func(closureMyObject myClass) {
        defer wg.Done()
        var tmpObj myClass
        tmpObj.AttributeName = closureMyObject.AttributeName
        destSlice = append(destSlice, tmpObj)
    }(myObject)
}
wg.Wait()

To verify the presence of data races, execute the following command:

go run -race play.go

The output will alert you to data races:

WARNING: DATA RACE
...

Resolving Concurrency Issues

To resolve this issue, protect the write access to the destSlice by employing a sync.Mutex:

var (
    mu        = &sync.Mutex{}
    destSlice = make([]myClass, 0)
)

var wg sync.WaitGroup
for _, myObject := range sourceSlice {
    wg.Add(1)
    go func(closureMyObject myClass) {
        defer wg.Done()
        var tmpObj myClass
        tmpObj.AttributeName = closureMyObject.AttributeName
        mu.Lock()
        destSlice = append(destSlice, tmpObj)
        mu.Unlock()
    }(myObject)
}
wg.Wait()

Alternatively, consider using a channel to asynchronously handle the appends:

var (
    appendChan = make(chan myClass)
    destSlice  = make([]myClass, 0)
)

var wg sync.WaitGroup
for _, myObject := range sourceSlice {
    wg.Add(1)
    go func(closureMyObject myClass) {
        defer wg.Done()
        var tmpObj myClass
        tmpObj.AttributeName = closureMyObject.AttributeName
        appendChan <- tmpObj
    }(myObject)
}
go func() {
    for {
        tmpObj := <-appendChan
        destSlice = append(destSlice, tmpObj)
    }
}()
wg.Wait()

The above is the detailed content of Why is `append` function not thread-safe for concurrent access in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn