Go Struct Concurrent Read and Write: Why Data Races Can Occur
In Go, concurrent read and write operations on structures without locks can potentially lead to data races. While this may not always result in fatal errors, it's crucial to understand the underlying issues.
The Data Race Problem in Structures
A data race occurs when multiple goroutines concurrently access a shared variable and at least one of those accesses is a write. In the case of structures, this means that two or more goroutines may be reading or writing different fields of the same structure at the same time.
Consider the following example, where multiple goroutines concurrently read and write a Metadata structure:
type Metadata struct { key bool } func concurrentStruct() { m := new(Metadata) for i := 0; i < 100000; i++ { go func(metadata *Metadata) { for { readValue := metadata.key if readValue { metadata.key = false } } }(m) go func(metadata *Metadata) { for { metadata.key = true } }(m) } select {} }
This example runs with a WARNING: DATA RACE, but does not result in a fatal error. This is because the data race occurs only on a single field of the structure (the key field). Since the other fields are not being accessed, the structure remains stable and the program can continue to run.
Resolving the Data Race
To eliminate data races, you must synchronize concurrent access to the structure using a lock. One way to achieve this is to use a read-write mutex, as shown in the following example:
type Metadata struct { mu sync.RWMutex key bool } func concurrentStructWithMuLock() { m := new(Metadata) go func(metadata *Metadata) { for { metadata.mu.Lock() readValue := metadata.key if readValue { metadata.key = false } metadata.mu.Unlock() } }(m) go func(metadata *Metadata) { for { metadata.mu.Lock() metadata.key = true metadata.mu.Unlock() } }(m) select {} }
With the addition of the read-write mutex, the data race is eliminated, and the program runs without error messages. This is because the mutex ensures that only one goroutine can access the structure at a time.
In conclusion, concurrent read and write operations on structures in Go can result in data races, even if the structure has multiple fields. It's crucial to use synchronization mechanisms, such as read-write mutexes, to prevent data races and ensure the correct operation of concurrent programs.
The above is the detailed content of How Can Concurrent Read and Write Operations on Go Structs Lead to Data Races?. For more information, please follow other related articles on the PHP Chinese website!