"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why is `append` function not thread-safe for concurrent access in Go?

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

Published on 2024-11-11
Browse:502

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 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3