Created
August 9, 2018 12:21
-
-
Save Deleplace/23be9bbddda74b9ead069d9f4e9262db to your computer and use it in GitHub Desktop.
This program is not racy, but it's not deterministic either.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
a := 0 | |
// This mutex protects variable a. | |
var mu sync.Mutex | |
// 2 tasks will be launched. The main goroutine will | |
// wait for them to complete. | |
var wg sync.WaitGroup | |
wg.Add(2) | |
go func() { | |
mu.Lock() | |
a = 22 | |
mu.Unlock() | |
wg.Done() | |
}() | |
go func() { | |
mu.Lock() | |
a = 33 | |
mu.Unlock() | |
wg.Done() | |
}() | |
wg.Wait() | |
// It is possible that 22 is printed, or 33. | |
fmt.Println(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment