package main
import (
"fmt"
"sync"
)
type httpPkg struct{}
func (httpPkg) Get(url string) {
fmt.Println("to get url=", url)
}
var http httpPkg
func main() {
var wg sync.WaitGroup
var urls = []string {
"http://www.baodu.com",
"http://goproxy.cn",
}
//
fmt.Printf("%p\n", &wg)
//
for index, url := range urls {
fmt.Printf("for-> %p\n", &wg)
wg.Add(1)
fmt.Println(index, url)
//独立函数方式
go doActionImp(&wg, index, url)
//lambda方式
//go func(index int, url string) {
// //
// fmt.Printf("%p\n", &wg)
// defer wg.Done()
// //
// fmt.Println(index, url)
// http.Get(url)
//}(index, url)
}
//
fmt.Println("waiting....")
wg.Wait()
fmt.Println("done")
}
func doActionImp(wg *sync.WaitGroup, index int, url string) {
fmt.Printf("%p\n", wg)
defer wg.Done()
fmt.Println(index, url)
http.Get(url)
}
参考上面的例子:
采用lambda方式写协程时,wg的上下文是同一个,其实可以理解在func main中的都是同一个;如果,实现放到了外面,则上下文就全变了,需要传引用(指针)才可以:
#gosetup
C:\Users\houwenbin\AppData\Local\Temp\___go_build_gonet_test__2_.exe #gosetup
0xc000062090
for-> 0xc000062090
0 http://www.baodu.com
for-> 0xc000062090
1 http://goproxy.cn
waiting....
0xc000062090
1 http://goproxy.cn
to get url= http://goproxy.cn
0xc000062090
0 http://www.baodu.com
to get url= http://www.baodu.com
done
Process finished with exit code 0