Created
March 18, 2013 03:02
-
-
Save physacco/5184718 to your computer and use it in GitHub Desktop.
Test the effect of sync.Once.
This file contains hidden or 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
| // Test the effect of sync.Once. | |
| // See another example: http://golang.org/pkg/sync/#Once | |
| package main | |
| import ( | |
| "fmt" | |
| "sync" | |
| "runtime" | |
| ) | |
| var a int | |
| var once sync.Once | |
| func setup() { | |
| a++ | |
| } | |
| func doprint() { | |
| once.Do(setup) | |
| fmt.Println(a) | |
| } | |
| func main() { | |
| runtime.GOMAXPROCS(2) | |
| // these 3 goroutines runs on the same CPU | |
| go doprint() | |
| go doprint() | |
| go doprint() | |
| // prevent the process from exit | |
| for { // infinite loop, consumes 100% CPU | |
| } | |
| } | |
| // Output: | |
| // 1 | |
| // 1 | |
| // 1 | |
| // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment