Skip to content

Instantly share code, notes, and snippets.

@taka-wang
Last active April 16, 2023 18:34
Show Gist options
  • Save taka-wang/455ff6a4884a719c0825 to your computer and use it in GitHub Desktop.
Save taka-wang/455ff6a4884a719c0825 to your computer and use it in GitHub Desktop.
golang mutex
// refer to http://stackoverflow.com/questions/8286806/go-programming-language-mutual-concurrent-execution
// https://gobyexample.com/mutexes
package main
import "sync"
var m sync.Mutex
var wg sync.WaitGroup
func routine1() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func routine2() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func main() {
wg.Add(1); go routine1()
wg.Add(1); go routine2()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment