-
-
Save ilmsg/4a5be855cf20320ae34dff518ba36ab3 to your computer and use it in GitHub Desktop.
golang mutex
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
// 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