The issue is not an optimization by the Go compiler, but rather a lack of synchronization. The assignment to i is not followed by any synchronization event, so it is not guaranteed to be observed by any other goroutine. In fact, an aggressive compiler might delete the entire i statement.
The Go Memory Model
The Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.
To serialize access, protect the data with channel operations or other synchronization primitives such as those in the sync and sync/atomic packages.
If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever.
Synchronization
In the following example, the assignment to a is not followed by any synchronization event, so it is not guaranteed to be observed by any other goroutine. In fact, an aggressive compiler might delete the entire go statement.
<code class="go">var a string func hello() { go func() { a = "hello" }() print(a) }</code>
The following example shows how to serialize access to i using a sync.Mutex.
<code class="go">package main import ( "sync" "time" ) func main() { mx := new(sync.Mutex) i := 1 go func() { for { mx.Lock() i++ mx.Unlock() } }() <-time.After(1 * time.Second) mx.Lock() println(i) mx.Unlock() }</code>
The above is the detailed content of Why Is My Goroutine\'s Value Not Visible to Others?. For more information, please follow other related articles on the PHP Chinese website!