Skip to content

Instantly share code, notes, and snippets.

@Deleplace
Created August 9, 2018 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deleplace/23be9bbddda74b9ead069d9f4e9262db to your computer and use it in GitHub Desktop.
Save Deleplace/23be9bbddda74b9ead069d9f4e9262db to your computer and use it in GitHub Desktop.
This program is not racy, but it's not deterministic either.
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