var a string var done bool func setup() { a = "hello, world" done = true } func doprint() { if !done { once.Do(setup) } print(a) } func twoprint() { go doprint() go doprint() }
Variables:
Functions:
Concurrency in main():
Potential Issues:
Possible Outcomes
Due to the lack of synchronization, the program's output is non-deterministic. Here are the possible scenarios:
Case 1: g() executes before f() modifies a and b:
0 0
or
CASE 2: If b = 2 is completed before g() but a = 1 is not, the output could be:
2 0
Key Observations
Data Race: The concurrent access to a and b without synchronization introduces a data race. This makes the program's behavior undefined and unpredictable
Fixing the Code
var a, b int var wg sync.WaitGroup func f() { a = 1 b = 2 wg.Done() } func g() { print(b) print(a) } func main() { wg.Add(1) go f() wg.Wait() g() }
var a, b int func f(done chan bool) { a = 1 b = 2 done <- true } func g() { print(b) print(a) } func main() { done := make(chan bool) go f(done) <-done g() }
Here, g() waits until f() sends a signal over the done channel.
The above is the detailed content of GO:lack of synchronization. For more information, please follow other related articles on the PHP Chinese website!