goroutines schedule by os,nobody can detertine how one goroutine run,you can run this code:
package main
import (
"fmt"
"os"
"sync"
)
func data_init(size int) []int {
ints := make([]int, 0)
for i := 0; i < size; i++ {
ints = append(ints, i)
}
return ints
}
//just go func in loop without parameter
func data_handle1(wgp *sync.WaitGroup, data *[]int) {
actual_data := *data
wg := *wgp
for _, value := range actual_data {
wg.Add(1)
go func() { // schedule this goroutine by os,but last value in actual_data can pass to heap memory,fucntion can get this data
wg.Done()
fmt.Println(value, ",pid=", os.Getpid())
}()
}
wg.Wait()
}
//run in for loop scop,but goroutine function passed by string type of value
func data_handle2(wgp *sync.WaitGroup, data *[]int) {
actual_data := *data
wg := *wgp
for _, value := range actual_data {
wg.Add(1)
go func(value int) {
wg.Done()
fmt.Println(value, ",pid=", os.Getpid())
}(value)
}
wg.Wait()
}
func main() {
size := 6
var wg sync.WaitGroup
data := data_init(size)
fmt.Println("data:", data)
fmt.Println("--------------go func() in loop-----------")
data_handle1(&wg, &data)
fmt.Println("--------------go func(string) in loop-----------")
data_handle2(&wg, &data)
}
Jietu20171114-160122@2x.jpg
gorooutine just cost a few kb,just run that code:
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
memConsumed := func() uint64 {
runtime.GC()
var s runtime.MemStats
runtime.ReadMemStats(&s)
return s.Sys
}
var c <-chan interface{}
var wg sync.WaitGroup
noop := func() {
wg.Done()
<-c
}
const numGoroutines = 1000000
wg.Add(numGoroutines)
before := memConsumed()
for i := numGoroutines; i > 0; i-- {
go noop() //noop already block,but every runing in own goroutine
}
wg.Wait()
after := memConsumed()
fmt.Printf("total %d goroutines,each consumed memory %.3fkb\n", numGoroutines, float64(after-before)/numGoroutines/1000)
}
Jietu20171114-160633@2x.jpg
网友评论