Junior — Middle
Can different threads interact with the same memory address simultaneously?
sobes.tech AI
Answer from AI
Yes, in Go, different goroutines (threads) can access the same memory address simultaneously. However, this can lead to race conditions if access is not synchronized. Synchronization mechanisms such as mutexes (sync.Mutex), channels (chan), or atomic operations from the sync/atomic package are used for safe interaction with shared memory.
Example of using a mutex to protect access to a shared variable:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
counter++
mu.Unlock()
}
Without such measures, concurrent access can lead to unpredictable program behavior.