Created
June 16, 2014 03:41
-
-
Save dz1984/1b48983905ecaa0f00df to your computer and use it in GitHub Desktop.
雨蒼的<Go學習筆記,3e>,關於Goroutines的練習程式。
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
// 練習Goroutine | |
package main | |
import ( | |
"math" | |
"sync" | |
) | |
func sum(id int) { | |
var x int64 | |
for i := int64(0); i < math.MaxUint32; i++ { | |
x += i | |
} | |
println(id, x) | |
} | |
func main() { | |
wg := new(sync.WaitGroup) | |
wg.Add(2) | |
for i := 0; i < 2; i++ { | |
go func(id int) { | |
defer wg.Done() | |
sum(id) | |
}(i) | |
} | |
wg.Wait() | |
} |
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
// 練習Gosched機制: Gosched很像yield,會暫停目前goroutine,讓給Thread給別人。 | |
package main | |
import ( | |
"runtime" | |
"sync" | |
) | |
type HandleFunc func(int) | |
func Handler(id int, handleFnc HandleFunc, wg *sync.WaitGroup) { | |
defer wg.Done() | |
handleFnc(id) | |
} | |
func HasGoSched(id int) { | |
for i := 0; i < 10; i++ { | |
println(id, i) | |
if i == 3 || i == 8 { | |
runtime.Gosched() | |
} | |
} | |
} | |
func SayHello(id int) { | |
println(id, "Hello World!") | |
} | |
func OtherProc(id int) { | |
for i := 0; i < 10; i++ { | |
println(id, i) | |
if i == 5 { | |
runtime.Gosched() | |
} | |
} | |
} | |
func main() { | |
wg := new(sync.WaitGroup) | |
wg.Add(3) | |
go Handler(0, HasGoSched, wg) | |
go Handler(1, SayHello, wg) | |
go Handler(2, OtherProc, wg) | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment